Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between eof(), fail(), bad(), and good() in C++ streams?

Tags:

c++

io

c++11

I am currently learning C++ from the C++ Primer 5th edition. I am confused about the behavior of the methods to check the status of a stream due to seemingly conflicting information. On page 312 it states

If any of badbit, failbit, or eofbit are set, then a condition that evaluates that stream will fail.

On the very next page, it says that s.fail() is

true if failbit or badbit in the stream is set

and that

the code that is executed when we use a stream as a condition is equivalent to calling !fail().

This doesn't make sense because any expression that uses fail() should only know about failbit and badbit (since those are what make up fail()'s value) and yet !fail() is equivalent to all three of badbit, failbit, and eofbit being false.

How do these seemingly contradictory statements fit together?

like image 629
john01dav Avatar asked Mar 29 '17 04:03

john01dav


1 Answers

The second and third statements are correct and in agreement with the C++ standard. The first one, then, is simply a mistake. Neither fail nor operator bool nor operator ! take into account the eofbit state of a stream. Only good and eof do.

In the usual course of events, trying to read past the end of the stream sets both the eofbit and failbit, which is one likely reason why this mistake was so easy to make.

like image 119
hobbs Avatar answered Sep 21 '22 14:09

hobbs