Search code examples
c++filestreamstandard-library

Not good stream at opening?


When I open a file in binary mode, does a situation exist where is_open() is true but good() is false ?

bool ok = false;
std::ifstream stream("test.dat", std::ios::binary)
if (stream.is_open())
{
    ok = stream.good();//Does a situation exist where the result of this is false ?
    stream.close();
}

Solution

  • No: the two-argument constructor of std::ifstream is required to set the failbit if file opening fails.

    §27.9.1.7[ifstream.cons]/2

    explicit basic_ifstream(const char* s, ios_base::openmode mode = ios_base::in);

    calls rdbuf()->open(s, mode | ios_base::in). If that function returns a null pointer, calls setstate(failbit).

    and, for open(),

    §27.9.1.4[filebuf.members]/2

    basic_filebuf<charT,traits>* open(const char* s, ios_base::openmode mode);

    Returns: this if successful, a null pointer otherwise