Section 6.4 Dealing with I/O Failures
File operations, such as opening and closing files, are often a source of runtime errors for various reasons. Well-written programs always should include error checking and Handling routines for possible problems dealing with files. Error checking and handling generally involves the programmer inserting statements in functions that perform I/O to check if any of the operations have failed. In C (the predecessor to C++), the system call to open a file returns a value after the function is called. A negative number means the operation failed for some reason, which the program can check to see if reading from a file is alright. In C++, a simple error checking mechanism is provided by the member function
fail()
:
in_stream.fail();
This function returns
true
only if the previous stream operation for in_stream was not successful, such as if we tried to open a non-existent file. If a failure has occured, in_stream may be in a corrupted state and it is best not to attempt any more operations with it.
The following example code fragment safely quits the program entirely in case an I/O operation fails:
#include <cstdlib< // for the fail member function #include <fstream< // for file I/O definitions #include <iostream< // for cout definition using namespace std; int main() { ifstream in_stream; // Try changing this to realFile.txt in_stream.open("realFile.txt"); if (in_stream.fail()) { cout << "Sorry, the file couldn't be opened!\n"; exit(1); // This exit value indicates an error happened (usual exit // value is 0) } return 0; }
After opening the “myFile.txt” file, the
if
conditional checks to see if there was an error. If so, the program will output the apologetic error message and then exit. The exit(1)
function from the library cstdlib
enables the program to terminate at that point and have it return a “1” versus a “0”, indicating an Error has occurred.
For more on Error Handling, see section 1.11.
You have attempted 1 of 1 activities on this page.