cplusplus.com cplusplus.com
cplusplus.com   C++ : Forums : General C++ Programming : How to find out if a file exists
  Search:
- -
C++
Information
Documentation
Reference
Articles
Sourcecode
Forums
Forums
Beginners
Windows Programming
UNIX/Linux Programming
General C++ Programming
Articles
Lounge
Jobs

-

question  How to find out if a file exists

Nate879 (22)
How do I find out if a file exists?
|
Zaita (1175)
Please be more specific with your question.

What operating system?
Compiler? etc.
|
Nate879 (22)
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 (312)
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.
|

This topic is archived - New replies not allowed.
Home page | Privacy policy
© cplusplus.com, 2000-2008 - All rights reserved - v2.2
Spotted an error? contact us