1. Flow status description

The c++ standard library defines its own set of state change rules for streams. In the ios_base class declared in ios_base.h, it defines an enumeration type _Ios_Iostate to represent the state of streams.

state instructions
badbit System level error encountered during input/output, set to badbit
eofbit When you read a file and you get to the end of the file, it’s set to eOFBit
failbit When an error occurs when data is written to or read from the stream buffer, it is set to failbit
goodbit When none of the above is available, it’s goodbit

Ios_base defines ioState _M_streambuf_state; To represent the state of the current flow.

2. Flow state operation function

The flow state operations are defined in the basic_ios class, which is a derivative of iOS_Base and is located in the header basic_ios.h. The basic_ios class is defined in the basic_ios class.

Note: The enumeration type _Ios_Iostate is named ioState.

The function prototype is as follows:

// Return the current flow status
iostate
  rdstate(a) const
  { return _M_streambuf_state; }

// By default, all abnormal states are cleared and set to goodbit
  void
  clear(iostate __state = goodbit);

// Append according to the incoming state based on the current flow state
  void
  setstate(iostate __state)
  { this->clear(this->rdstate() | __state); }

// Return true if the current state is goodbit, false otherwise
  bool
  good(a) const
  { return this->rdstate() = =0; }

Return true if the current flow state is eofBit, false otherwise
  bool
  eof(a) const
  { return (this->rdstate() & eofbit) ! =0; }

// Return true if the current flow status is failbit, false otherwise
  bool
  fail(a) const
  { return (this->rdstate() & (badbit | failbit)) ! =0; }

// Return true if the current stream state is badbit, false otherwise
  bool
  bad(a) const
  { return (this->rdstate() & badbit) ! =0; }
Copy the code

So if we want to actively set the flow state, we can use setstate, to clear all abnormal states, we can use clear, and to determine whether the current flow state is normal, we can use good.

Here is a diagram to summarize the relationship between the two classes: