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");
}
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With