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?

5/23/2017 12:26:15 PM

Accepted Answer

Use boost::filesystem:

#include <boost/filesystem.hpp>

if ( !boost::filesystem::exists( "myfile.txt" ) )
  std::cout << "Can't find my file!" << std::endl;
5/28/2012 7:05:52 AM

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

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow