Search I/O file data
I have created a section in my program such that it will prompt user to enter the filename. From this, it will create the file with the filename the user have entered.
However, I would like to know how can I check if the file already exists? If it already exists, do not create the file and simply open the existing file and add more data from the last line.
Here's part of the code
cout << "Enter filename: ";
cin >> pfile;
/* open an existing configuration file to check if the filename exists
(I'm not sure how to check... this simply open the file) */
infile.open("config.cfg", ios::in, 0);
// create file base on what user specify
// open configuration file and store filename in it
outfile.open("config.cfg", ios::out, 0);
outfile << pfile;
Simply open it with the right "ios" flag. There are flag types for appending, truncating, etc.
Hmm, i'm not really sure how to go about it. Mind showing it to me? I only know how to use ios::out, ios::in etc.
* Checks if a file exists.
* file - name of the file
* Returns: true if file exists, false otherwise.
bool doesFileExist( char * file )
ifstream input( file, ios::in ) ;
if ( input.is_open() ) // if file can be opened, if exists
return true ;
return false ;
A few seconds on Google will give you some examples. Most everything you'll ever need can be found there; in the event no one is around here, or you feel like answering your own questions. :)
There is no real need to ever check if it exists, if you're just going to append to it anyway.
Thanks Dante :)
I get your idea quzah... but I guess i need to read more on how I/O file system works ;)
BTW, I've got a question. Let's say I have 2 base class, 2 derived class. Each base class constructor contains all the question that will prompt the user and is called when I do a
in my main() switch statement. So, I would like to know, where should I actually place the file open/close? I have tried to place inside the constructor but everytime, it overwrites the information in it.
Instance[array] = new BaseClassName;