How to find out if a file exists
Nate879 (22)
May 6, 2008 at 12:53am UTC
How do I find out if a file exists?
Zaita (2292)
May 6, 2008 at 1:01am UTC
Please be more specific with your question.
What operating system?
Compiler? etc.
Nate879 (22)
May 6, 2008 at 1:11am UTC
There should be a portable way to do this, that wouldn't depend on OS, compiler, etc.
If there isn't, I am using Windows XP + MinGW.
ropez (310)
May 6, 2008 at 4:35am UTC
Typically you only check if the file exists when you want to read from it:
1 2 3 4
ifstream ifile(filename);
if (ifile) {
// The file exists, and is open for input
}
I think if you only need to check if the file exists, the most portable way is to test if you can open it:
1 2 3 4 5
bool fexists(const char *filename)
{
ifstream ifile(filename);
return ifile;
}
The return statement should cast the file object to a boolean which is true if the file exists. The file is automatically closed at the end of the function scope.
Topic archived. No new replies allowed.