How to check if a file exists in C++ with fstream::open()

It says it sets the failbit if the file couldn't be opened. So you can check for that bit:

fileStream.open("logs.txt");
if (fileStream.fail()) {
    // file could not be opened
}

Actually, just if (fileStream) would work here as well, since ios (a base class of ifstream, ofstream, and fstream) has a conversion operator to bool.

Don't worry about the failure exception. You can request exceptions to be thrown on failure by calling ios::exceptions but by default exceptions are not thrown on failure.

Note that this doesn't tell you why the file couldn't be opened. It could be that the file didn't exist, that a directory in the path didn't exist, you don't have permission to open the file, your program has reached the limit on the number of files it can open, and so on. There is no portable way to determine the reason.


Note that there are difference between "File exist" and "File can be opened".

To check if file exist (and you indeed do not need to open/read/write the file), use fstat or its c++ counterpart - you don't need any permission to query the info.

Note that if you want to check file exist before open it, you are doing it wrong. Condition may have changed between your checking and the actual attempt to open the file. In general, you just directly open the file with the open/creation options without previously checking.


Your method doesn't check for existence, but rather accessibility. It is possible to check existence like this:

#include <sys/stat.h>

inline bool exists (const std::string& filename) {
  struct stat buffer;   
  return (stat (filename.c_str(), &buffer) == 0); 
}

In C++14 it is possible to use this:

#include <experimental/filesystem>

bool exist = std::experimental::filesystem::exists(filename);

& in C++17: (reference)

#include <filesystem>

bool exist = std::filesystem::exists(filename);

Tags:

C++