Vincent
Vincent

Reputation: 60371

Successfully open but not good?

In C++, is there a case where std::ifstream open() can be successful, but std::ifstream good() can be false ?

EDIT : tested with g++ 4.7.1

#include <iostream>
#include <fstream>
int main(int argc, char *argv[])
{
    std::ifstream filestream("testfile");
    std::cout<<filestream.good()<<std::endl;
    std::cout<<filestream.eof()<<std::endl;
    std::cout<<filestream.fail()<<std::endl;
    std::cout<<filestream.bad()<<std::endl;
    return 0;
}

will return : 1, 0, 0, 0 for an empty file which means good = TRUE and eof = fail = bad = FALSE. Is it normal ?

Upvotes: 9

Views: 7753

Answers (3)

James Kanze
James Kanze

Reputation: 153909

After verifying the actual text in the standard, I don't think eofbit is allowed to be set after an open: badbit may be set if the actual open throws an exception (I think—the standard doesn't really say what should happen in this case); failbit should be set if the open fails, or if the seek after the open (if ate is set) fails; but there doesn't seem to be any case where eofbit may be set.

Not that calling std::istream::good() is a good solution in this case. (It would be interesting to know what the OP is trying to achieve. Whatever it is, calling std::istream::good() is probably not the right solution.)

If std::ifstream::good() returns false, the next input will fail. If it returns true, it tells you nothing: the next input may succeed, but it might also fail.

Upvotes: 4

Steve Jessop
Steve Jessop

Reputation: 279255

ifstream::open returns void, so be careful exactly what you mean by saying it's "successful".

The standard says for basic_ifstream::open (27.9.1.9):

Effects: Calls rdbuf()->open(s, mode | ios_base::in). If that function does not return a null pointer calls clear(), otherwise calls setstate(failbit) (which may throw ios_base::failure)

So, if the call to open on the filebuf returns a value indicating success, then ifstream::open clears all the error bits, and so good() necessarily returns true.

If the call to open on the filebuf returns a value indicating failure, then ifstream::open can nevertheless return without throwing an exception. This behavior could be confused with "success", but in this case good() returns false because the failbit is set.

It's not entirely clear to me why this sets the failbit rather than the badbit, but I don't think my lack of understanding gets in the way of reporting the facts :-)

Upvotes: 1

Borgleader
Borgleader

Reputation: 15916

If the file is empty the eofbit will be triggered but the file will still be open so yes.

Upvotes: 2

Related Questions