What’s the best way to check if a file exists in C++? (cross platform)
I have read the answers for What's the best way to check if a file exists in C? (cross platform), but I'm wondering if there is a better way to do this using standard c++ libs? Preferably without trying to open the file at all.
Both stat
and access
are pretty much ungoogleable. What should I #include
to use these?
Use boost::filesystem:
#include <boost/filesystem.hpp>
if ( !boost::filesystem::exists( "myfile.txt" ) )
{
std::cout << "Can't find my file!" << std::endl;
}
Be careful of race conditions: if the file disappears between the "exists" check and the time you open it, your program will fail unexpectedly.
It's better to go and open the file, check for failure and if all is good then do something with the file. It's even more important with security-critical code.
Details about security and race conditions: http://www.ibm.com/developerworks/library/l-sprace.html
I am a happy boost user and would certainly use Andreas' solution. But if you didn't have access to the boost libs you can use the stream library:
ifstream file(argv[1]);
if (!file)
{
// Can't open file
}
It's not quite as nice as boost::filesystem::exists since the file will actually be opened...but then that's usually the next thing you want to do anyway.