State of an I/O Stream
We know any of the following can cause an input stream to enter the fail state:
- Invalid input data
- An attempt to read beyond the end of a file
- An attempt to open a nonexistent file to input
C++ provides a way to test the state of a stream: The stream name used
in the expression returns true
if the state is OK and
false
if the file stream is in a fail state.
Here is an example program that reads four floating point data values
from a file and writes them to another file in reverse order.
Note that inData
and outData
are two varibales in the program;
"inputfile.txt"
and "outputfile.txt"
are character strings.
inputfile.txt
is the name of the input data file that we
have created; outputfile.txt
is the name of the output data file where
the answers are stored.
If the input file inputfile.txt
cannot be found, 1
is returned to the
operating system.
If the output file outputfile.txt
cannot be opened or created,
2
is returned to the operating system.
If the data format read from inData is incorrect or there is not enough data, 3 is returned to the operating system.
If there is no input and output error, 0 is returned to the operating system. Notice that the main is exited as soon as a value is returned. Therefore, Returning 0 value means normal completion of a program; returning any other value signals an error. When you write your own program, you may choose the value to return to indicate different error conditions.
You can use a plain text editor or your Desktop IDE to create the input data file according to the requirements of the data types and format in your program. The input data file must exist and contain correct data before you run the program. Otherwise, you will get input failure.
For example, in the preceding IODemo program, the input file should look like this:
5.5 6.6 7.7 8.8
You may run the program and and test the state of the I/O stream.