ifstream: check if opened successfully

Philipp picture Philipp · Nov 17, 2010 · Viewed 37.1k times · Source

A colleague just told me that this code:

std::ifstream stream(filename.c_str());
if (!stream)
{
    throw std::runtime_error("..");
}

would be wrong. He said ifstream evaluates to 0 if opening is successful. My code works, but I wanted to find the documentation but didn't see where it says how to check if opening was successful. Can you point me to it?

Answer

Oliver Charlesworth picture Oliver Charlesworth · Nov 17, 2010

operator! is overloaded for std::ifstream, so you can do this.

In my opinion, though, this is a horrible abuse of operator overloading (by the standards committee). It's much more explicit what you're checking if you just do if (stream.fail()).