To test for fatal I/O error.
bool bad() const
Use the member function bad() to test if a fatal input or output error occurred which sets the badbit flag in the stream.
Returns true if badbit is set in rdstate().
basic_ios::fail()
// The file ewl-test contains: // abcdefghijklmnopqrstuvwxyz #include <iostream> #include <fstream> #include <cstdlib> char * inFile = "ewl-test"; using namespace std; void status(ifstream &in); int main() { ifstream in(inFile); if(!in.is_open()) { cout << "could not open file for input"; exit(1); } int count = 0; int c; while((c = in.get()) != EOF) { // simulate a failed state if(count++ == 4) in.setstate(ios::failbit); status(in); } status(in); in.close(); return 0; } void status(ifstream &in) { // note: eof() is not needed in this example // if(in.eof()) cout << "EOF encountered \n"; if(in.fail()) cout << "Non-Fatal I/O Error \n"; if(in.good()) cout << "GoodBit set \n"; if(in.bad()) cout << "Fatal I/O Error \n"; }
Result:
GoodBit set GoodBit set GoodBit set GoodBit set Non-Fatal I/O Error Non-Fatal I/O Error