How to find out if a file exists

How do I find out if a file exists?
Please be more specific with your question.

What operating system?
Compiler? etc.
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.
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.