I have a program that does things with files. I want to check if a file exists, and if it doesn't, create it with a default message. I don't know how I'd check if it exists. Could you tell me?
Printable View
I have a program that does things with files. I want to check if a file exists, and if it doesn't, create it with a default message. I don't know how I'd check if it exists. Could you tell me?
Code:filein.open("test.txt");
if(fin.fail())
{
// do something
}
NOTE: keep in mind that in this particular case the file test.txt has to be in the same directory as you executable file, otherwise you would have to specify the entire path i.e.Code:#include<iostream.h>
#include<fstream.h>
#include<stdlib.h> // uses exit() function...
int main()
{
ifstream fin("test.txt");
if( fin.fail() )
{
cout << "Can't find or open a given file!!! Exiting. \n";
exit(1); // terminates the program execution...
}
else
{
cout << "File exists and is open. Now will get closed. \n";
fin.close();
}
return 0;
}
Code:
ifstream fin("c:\\myfile\\someothercrap\\test.txt");
hope that helps...