C++: Check if file exists
Problem:
In C++ you want to check if a given file exists, but you can’t use stat()
because your code needs to work cross-plaform.
Solution
This solution is 100% portable (stat() isn’t, even if it it’s widely support), but note that it opens the file, so it might fail if it exists, but the user who is running the program isn’t allowed to access it
#include <fstream>
bool fexists(const char *filename) {
std::ifstream ifile(filename);
return (bool)ifile;
}
If you have the filename as std::string
rather than as cstring, you can use this snippet:
#include <fstream>
bool fexists(const std::string& filename) {
std::ifstream ifile(filename.c_str());
return (bool)ifile;
}
If you know for a fact that you have access to stat() I recommend using stat instead. See this followup blog post for an example on how to do this.