ifstream: how to tell if specified file doesn't exist

Viewed 116183

I want to open a file for reading. However, in the context of this program, it's OK if the file doesn't exist, I just move on. I want to be able to identify when the error is "file not found" and when the error is otherwise. Otherwise means I need to quit and error.

I don't see an obvious way to do this with fstream.


I can do this with C's open() and perror(). I presumed that there was a fstream way to do this as well.

8 Answers

A better way:

std::ifstream stream;
stream.exceptions(std::ifstream::failbit | std::ifstream::badbit);
stream.open(fileName, std::ios::binary);

Straight way without creating ifstream object.

if (!std::ifstream(filename))
{
     // error! file doesn't exist.
}
Related