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?
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?
Stupid things pop singers say
"I get to go to lots of overseas places, like Canada."
- Britney Spears
"I love what you've done with the place!"
-Jessica Simpson upon meeting the Secretary of Interior during tour of the White House
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...