What’s the best way to check if a file exists in C++? (cross platform)

c0m4 picture c0m4 · Nov 6, 2008 · Viewed 109.5k times · Source

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?

Answer

Andreas Magnusson picture Andreas Magnusson · Nov 6, 2008

Use boost::filesystem:

#include <boost/filesystem.hpp>

if ( !boost::filesystem::exists( "myfile.txt" ) )
{
  std::cout << "Can't find my file!" << std::endl;
}