Sunday 9 June 2019

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




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");
}

Answer



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.


No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...