Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

I'm using fstream library to work with files. Basically, I need to know if a certain file exists or not. In c++ documentation online, about open(), it reads:

Return Value

none

If the function fails to open a file, the failbit state flag is set for the stream (which may throw ios_base::failure if that state flag was registered using member exceptions).

It says not return value is specified. But in case of failure, a flag is set. My question is that, I should I then access that flag, or to better ask, how should I see if open() is successful or not.

I have this code so far:

int Log::add()
{
    fstream fileStream;

    fileStream.open("logs.txt");
}
like image 977
Mostafa Talebi Avatar asked Aug 10 '14 05:08

Mostafa Talebi


1 Answers

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);
like image 157
Amit G. Avatar answered Sep 24 '22 03:09

Amit G.