Whats the best way to check and see if a file exists?
Printable View
Whats the best way to check and see if a file exists?
Try and open it. As long as you use the standard fstream header trying to open a file using an ifstream object that doesn't exist will fail.
ifile ifstream;
ifile.open("filename.ext");
When i do that it creates the file, weather it exists or not.
And the ifstream::open() function dosent return a value, so how do i know if it failed?
I was thinking i might could use the eof member somehow?
I tried
if(ifile.eof) createfile();
Are you sure you're using the standard header files (the ones without the h extension)? Try this -
Code:#include <iostream>
#include <fstream>
using namespace std;
int main()
{
ifstream in;
in.open("doesnotexist.txt");
if(!in.is_open())
cout << "File doesn't exist"<<endl;
return 0;
}