Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

Check If a Variable FileName exists

Posted on 2014-09-28
14
Medium Priority
?
149 Views
Last Modified: 2014-09-29
Hi folks, I'm trying to check if a file that has a variable name exists in a certain path, but have not been successful until now.
The code is below so that you guys can better understand what I'm trying to do... So any help would be much appreciated...

//---------------------------------------------------------------------------
#include <time.h>
#include <sys/types.h>
#include <stdio.h>
#include <errno.h>
#include <sstream>
#include <vcl.h>
#pragma hdrstop
#include <windows.h>
#include <iostream>
#include <fstream>
#include <cstdlib> //Needed for exit()
#include "Shlwapi.h"
#include "Teste1.h"
#include <sys/stat.h>
using namespace std;
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma resource "*.dfm"
TForm1 *Form1;
//---------------------------------------------------------------------------
__fastcall TForm1::TForm1(TComponent* Owner)
	: TForm(Owner)
{
}
//---------------------------------------------------------------------------
void __fastcall TForm1::Button1Click(TObject *Sender)
{

	int hour;
	int day;
	int month;
	int year;
	hour= 98;  //Ignores the 9 in the first case so it means 8
	day= 28;
	month= 99;  //Ignores the 9 in the first case so it means 9
	year= 14;
	//working fine
	stringstream ss;

	//address and name of the files
	//create file name
	ss << "C:/Users/rodrigo/Desktop/Calendar/" << hour<< day<< month<< year<<".txt";
	string address;
	address = ss.str();
	//Working after changing the argument to the below one
	ofstream fout(address.c_str());
	fout<<hour<<day<<month<<year;
	fout.close();


}
//---------------------------------------------------------------------------

Open in new window


The Idea is to create files named as "HourDayMonthYear.txt", where each has 2 numbers to represent them, and afterwards to check if the file exists.

Any help would be much appreciated.
Cheers.
0
Comment
Question by:Rodric MacOliver
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 4
  • 4
  • 4
  • +2
14 Comments
 
LVL 25

Expert Comment

by:chaau
ID: 40349271
Oh Delphi, Delphi (i.e. C+ Builder). It was so long time ago...
Why don't you just use the Format function:
string address;
address = Format("C:/Users/rodrigo/Desktop/Calendar/%02d%02d%02d%02d.txt",  year, month, day, hour);

Open in new window

BTW, I prefer to start with Year Month Day Hour. In this case the file names will have better sort order.
To check if the file exists you can use either Win32 API GetFileAttributes() function or Delphi's own FileExists() function
if(FileExists(address))
   // do something

Open in new window

0
 
LVL 12

Expert Comment

by:trinitrotoluene
ID: 40349290
The filename that gets created by your code is this :

"C:/Users/rodrigo/Desktop/Calendar/98289914.txt"

so the "9"s are not ignored as stated in your comment. That's the reason you see a file not found

I'm not sure if you are using the extra "9"s as a placeholder but a better way would be to pad with leading zeros

Something like
int hour;
	int day;
	int month;
	int year;
	hour= 8;  
	day= 28;
	month= 9;  
	year= 14;
	//working fine
	stringstream ss;

	//address and name of the files
	//create file name
	//pad with leading 0s
	ss << "C:/Users/rodrigo/Desktop/Calendar/" << setw(2)<<setfill('0')<<hour<< day<< setw(2)<<setfill('0')<<month<< year<<".txt";
	string address;
	address = ss.str();
	//Working after changing the argument to the below one
	ofstream fout(address.c_str());
	fout<<hour<<day<<month<<year;
	fout.close();

Open in new window


hope this helps
0
 
LVL 12

Expert Comment

by:trinitrotoluene
ID: 40349291
remember to

#include <iomanip>

Open in new window

0
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 12

Expert Comment

by:trinitrotoluene
ID: 40349292
I've padded only for the hour and month. You will need to do it for the day and year as well
0
 

Author Comment

by:Rodric MacOliver
ID: 40349297
trinitrotoluene, I know that it is not ignore, I didn't create the code for that yet, what I need it a way to check if a file,
in this case:

 "C:/Users/rodrigo/Desktop/Calendar/" << hora << dia << mes << ano<<".txt"

Exists or not.
0
 
LVL 25

Expert Comment

by:chaau
ID: 40349300
Use FileExists() function.
if(FileExists(address))
   // do something

Open in new window

0
 

Author Comment

by:Rodric MacOliver
ID: 40349322
chaau, I get the following errors using the FileExists() function:
[bcc32 Error] Teste1.cpp(47): E2034 Cannot convert 'string' to 'UnicodeString'
[bcc32 Error] Teste1.cpp(47): E2342 Type mismatch in parameter 'FileName' (wanted 'const UnicodeString', got 'string')
0
 
LVL 25

Expert Comment

by:chaau
ID: 40349331
Use this:
if(FileExists(UnicodeString(address)))
   // do something

Open in new window

0
 

Author Comment

by:Rodric MacOliver
ID: 40349332
chaau, didn't work.

Errors:
[bcc32 Error] Teste1.cpp(47): E2285 Could not find a match for 'UnicodeString::UnicodeString(string)'
[bcc32 Error] Teste1.cpp(47): E2031 Cannot cast from 'string' to 'UnicodeString'
0
 
LVL 25

Assisted Solution

by:chaau
chaau earned 664 total points
ID: 40349344
You are right. I do not have the Builder on my machine and could not test. Try this:
if(FileExists(UnicodeString(address.c_str)))
   // do something

Open in new window

0
 

Author Comment

by:Rodric MacOliver
ID: 40349350
chaau, now only one error:
[bcc32 Error] Teste1.cpp(47): E2235 Member function must be called or its address taken
0
 
LVL 16

Expert Comment

by:George Tokas
ID: 40349461
if(FileExists(UnicodeString(address.c_str())))
0
 
LVL 12

Assisted Solution

by:trinitrotoluene
trinitrotoluene earned 668 total points
ID: 40349482
rodrigo:

here's a simple function I wrote.
call this function whenever you want to check for a file's existence. Alternately you can use the implementation directly

bool doesFileExist(const char *filename)
{
  std::ifstream myfile(filename);
  if(!myfile) //file doesn't exist
    return false;
 else
   return true;
}

Open in new window

0
 
LVL 35

Accepted Solution

by:
sarabande earned 668 total points
ID: 40350507
[bcc32 Error] Teste1.cpp(47): E2034 Cannot convert 'string' to 'UnicodeString'
 [bcc32 Error] Teste1.cpp(47): E2342 Type mismatch in parameter 'FileName' (wanted 'const UnicodeString', got 'string')
if your default is UNICODE strings, you may consider using std::wstring instead of std::string and std::wostringstream instead of std::stringstream:

//---------------------------------------------------------------------------
....
#include <string>
#include <fstream>
#include <sstream>
#include <iomanip>
#include <sys/stat.h>

void __fastcall TForm1::Button1Click(TObject *Sender)
{
     int hour;
     int day;
     int month;
     int year;
     hour= 8;  // no, don't use 98
     day= 28;
     month= 9;  // no, don't use 99
     year= 2014;

     std::wostringstream wss;
     //address and name of the files
     //create file name as YYMMDDHH.txt (would sort better in the folder)
     wss << L"C:/Users/rodrigo/Desktop/Calendar/" 
             << std::setw(2) << std::right << std::setfill('0') << (year%100)
             << std::setw(2) << std::right << std::setfill('0') << month
             << std::setw(2) << std::right << std::setfill('0') << day
             << std::setw(2) << std::right << std::setfill('0') << hour
             <<L".txt";   
     std::wstring ws = wss.str();
     struct _wstat fs = { 0 };
     std::wofstream wof;
     if (_wstat(ws.c_str(), &fs) == 0)
     {
           wof.open(ws.c_str(), std::ios::app || std::ios::out);
           wof << "appended line" << std::endl;
     }
     else 
    {   
          wof.open(ws.c_str());
          wof << "1. line" << std::endl;
    }
    wof.close();
}

Open in new window

note, using wofstream instead of ofstream only means that the stream is capable to handle wide strings for filename and input. it doesn't mean that the file becomes a wide-char text file.

if you omit all '_w' and 'w' and L prefix in the above code it would use ansi character set and not wide characters but the results are the same.

Sara
0

Featured Post

Hire Technology Freelancers with Gigs

Work with freelancers specializing in everything from database administration to programming, who have proven themselves as experts in their field. Hire the best, collaborate easily, pay securely, and get projects done right.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

When writing generic code, using template meta-programming techniques, it is sometimes useful to know if a type is convertible to another type. A good example of when this might be is if you are writing diagnostic instrumentation for code to generat…
Written by John Humphreys C++ Threading and the POSIX Library This article will cover the basic information that you need to know in order to make use of the POSIX threading library available for C and C++ on UNIX and most Linux systems.   [s…
The goal of the tutorial is to teach the user how to use functions in C++. The video will cover how to define functions, how to call functions and how to create functions prototypes. Microsoft Visual C++ 2010 Express will be used as a text editor an…
The viewer will learn how to user default arguments when defining functions. This method of defining functions will be contrasted with the non-default-argument of defining functions.

721 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question