Testing Stream States in C++

The functions eof(), fail(), good(), and bad() can be used to test the states of stream operations.

You have used the eof() function and fail() function to test the states of a stream. C++ stream state provides several more functions in a stream for testing stream states. Each stream object contains a set of bits that act as flags. These bit values (0 or 1) indicate the state of a stream. Table 13.2 lists these bits.

The states of the I/O operations are represented in these bits. It is not convenient to directly access these bits. C++ provides member functions in the I/O stream object to test them. These functions are listed in Table 13.3.

Listing 13.9 gives an example to detect the stream states.

Listing 13.9 ShowStreamState.cpp

1 #include <iostream>
2
#include <fstream>
3
#include <string>
4
using namespace std;
5
6
void showState(const fstream&);
7
8
int main()
9 {
10    fstream inout;
11
12   
// Create an output file
13    inout.open(“temp.txt”, ios::out);
14    inout <<
“Dallas”;
15    cout <<
“Normal operation (no errors)” << endl;
16    showState(inout);
17    inout.close();
18

19    // Create an input file
20    inout.open(“temp.txt”, ios::in);
21
22   
// Read a string
23    string city;
24    inout >> city;
25    cout <<
“End of file (no errors)” << endl;
26    showState(inout);
27
28    inout.close();
29
30   
// Attempt to read after file closed
31    inout >> city;
32    cout <<
“Bad operation (errors)” << endl;
33    showState(inout);
34
35   
return 0;
36 }
37
38
void showState(const fstream& stream)
39 {
40    cout <<
“Stream status: ” << endl;
41    cout <<
” eof(): ” << stream.eof() << endl;
42    cout <<
” fail(): ” << stream.fail() << endl;
43    cout <<
” bad(): ” << stream.bad() << endl;
44    cout <<
” good(): ” << stream.good() << endl;
45 }

The program creates a fstream object using its no-arg constructor in line 10, opens temp.txt for output in line 13, and writes a string Dallas in line 14. The state of the stream is displayed in line 15. There are no errors so far.

The program then closes the stream in line 17, reopens temp.txt for input in line 20, and reads a string Dallas in line 24. The state of the stream is displayed in line 26. There are no errors so far, but the end of file is reached.

Finally, the program closes the stream in line 28 and attempts to read data after the file is closed in line 31, which causes an error. The state of the stream is displayed in line 33.

When invoking the showState function in lines 16, 26, and 33, the stream object is passed to the function by reference.

Source: Liang Y. Daniel (2013), Introduction to programming with C++, Pearson; 3rd edition.

Leave a Reply

Your email address will not be published. Required fields are marked *