The Input/Output system in C++, holds information about the result of every I/O operation. The current status is kept in an object from type io_state, which is an enumerated type (just like open_mode) that has the following values:
- godbit -> No errors.
- eofbit -> End of file has been reached
- failbit -> Non-fatal I/O error
- badbit -> Fatal I/O error
There are two ways, to receive information about the I/O status. One of them is by calling the function rdstate(). It returns the current status of the error-flags (the above mentioned). For example, the rdstate() function will return goodbit if there were no errors.
The other way to check the I/O status is by using any of the following function:
bool eof(); // remember this one? “Read until the end of the file has been reached!”
bool fail(); // and this one, too… Check if the file opening was successfull
The function bad() returns true, if the badbit flag is up. The fail() function returns true if the failbit flag is up. The good() function returns true if there were no errors (the goodbit flag is up). And the eof() function returns true if the end of the file has been reached (the eofbit flag is up).
If an error occurred, you will have to clear it if you want your program to continue properly. To do so, use the clear() function, which takes one parameter. The parameter should be the flag you want to put to be the current status. If you want your program to continue “on clear”, just put ios::goodbit as parameter. But notice that the clear() function can take any flag as parameter. You will see that in the code examples bellow.
I will now show you some example code that will confirm your knowledge.
Simple status check
//Replace FileStream with the name of the file stream handle
if(FileStream.rdstate() == ios::eofbit)
cout << "End of file!\n";
if(FileStream.rdstate() == ios::badbit)
cout << "Fatal I/O error!\n";
if(FileStream.rdstate() == ios::failbit)
cout << "Non-fatal I/O error!\n";
if(FileStream.rdstate() == ios::goodbit)
cout << "No errors!\n";
The clear() function
ofstream File1("file2.txt"); //create file2.txt
//this bellow, will return error, because I use the ios::noreplace
//open_mode, which returns error if the file already exists.
//The error that the last line returned is ios::failbit, so let’s show it
if(Test.rdstate() == ios::failbit)
cout << "Error...!\n";
Test.clear(ios::goodbit); //set the current status to ios::goodbit
if(Test.rdstate() == ios::goodbit) //check if it was set correctly
cout << "Fine!\n";
Test.clear(ios::eofbit); //set it to ios::eofbit. Useless.
if(Test.rdstate() == ios::eofbit) //and check again if it is this flag indeed
cout << "EOF!\n";
Instead using flags, you can use a function that actually does the same - checks if specific flag is up.