- C++ Course Basics
- C++ Tutorial
- C++ Basic Syntax
- C++ Identifiers
- C++ Character Set
- C++ Input/Output Operator
- C++ Variables
- C++ Data Types
- C++ Formatting Output
- C++ Operators
- C++ Assignment Operator
- C++ Type Conversion
- C++ Program Control
- C++ if and if-else
- C++ switch
- C++ loops
- C++ break and continue
- C++ Functions
- C++ Functions
- C++ Prototype and Definition
- C++ Function Call
- C++ Function Types
- C++ Friend Function
- C++ Function Overloading
- C++ Arrays and Strings
- C++ Arrays
- C++ One-Dimensional Arrays
- C++ Strings
- C++ String Functions
- C++ Structures
- C++ Structures
- C++ Nested Structure
- C++ Structure Array
- C++ Pass Structure to Function
- C++ Pointers
- C++ Pointers
- C++ Memory Map
- C++ Declare Initialize Pointers
- C++ Pointers and Structures
- C++ Object-Oriented
- C++ Object-Oriented
- C++ Classes and Objects
- C++ Constructors and Destructors
- C++ Objects as Function Arguments
- C++ Pointers and Objects
- C++ Data Structure
- C++ Linked List
- C++ Stack
- C++ Queues
- C++ File Handling
- C++ File Handling
- C++ Opening and Closing Files
- C++ Steps to Process Files
- C++ Sequential I/O Operations
- C++ Detecting EOF
- C++ File Pointers Random Access
- C++ Binary Files Operations
- C++ Error Handling
- C++ Misc
- C++ typedef
- C++ #define
- C++ Date and Time
- C++ Examples
- C++ Examples
C++ Error Handling During File Operation
Sometimes, during file operations, errors may also creep in. For example, a file being opened for reading might not exist. Alternatively, a file name used to create a new file may already exist. Alternatively, an attempt could be made to read past the end of the file. Or such an invalid operation may be performed. There might not be enough space on the disc for storing data.
C++ file streams inherit "stream-state" members from the ios class. These members store information on the status of a file that is currently being used and are used to check for errors like the ones described above and to ensure that processing goes smoothly. An integer that contains the following flags' encoding is used to store the current state of the I/O system. These flags are as follows:
Name | Meaning |
---|---|
eofbit | 1 when end-of-file is encountered, 0 otherwise. |
failbit | 1 when a non-fatal I/O error has occurred, 0 otherwise |
badbit | 1 when a fatal I/O error has occurred, 0 otherwise |
goodbit | 0 value |
C++ Error Handling Functions
There are several error handling functions supported by class ios that help you read and process the status recorded in a file stream.
The following list describes these error handling functions and their meaning:
- int bad(): If an invalid operation was attempted or any error that cannot be recovered from occurred, this function will return a value that is not zero. On the other hand, if it is zero, which indicates a false value, it is possible to recover from any other error that was reported and carry on with operations.
- int eof(): If the end of the file is reached while reading, this function returns a non-zero value (a true value); otherwise, it returns zero (false value).
- int fail(): If an input or output operation was unsuccessful, this function will return a value that is not zero (true).
- int good(): If there was no error, this function will return a value that is not zero (true). This indicates that the functions described above are all invalid. For instance, if the function fin.good() returns true, it indicates that the stream with the name fin is functioning normally and that we can move on to the next step of performing I/O operations. After it has returned zero, there will be no more operations that can be performed.
- clear(): Resets the error state, allowing subsequent operations to be attempted.
eof() returns true if eofbit is set, whereas bad() returns true if badbit is set. fail() returns true if the failbit is set, whereas good() returns true if there are no errors. If not, they return false.
These functions may be used at the appropriate points in a program to determine the status of a file stream and take the appropriate corrective action. For instance:
: ifstream fin; fin.open("master", ios::in); while(!fin.fail()) { : // process the file } if(fin.eof()) { : // terminate the program } else if(fin.bad()) { : // report fatal error } else { fin.clear(); // clear error-state flags : } :
C++ Error Handling Example
Here is an example program illustrating error handling during file operations in a C++ program:
#include <iostream> #include <fstream> #include <string> using namespace std; int main() { string myline, myfile; char ch; cout << "Enter file name: "; getline(cin, myfile); ifstream ifs(myfile); if (ifs) { cout << "The entered file already exists. Please try again.\n"; return 0; } else { ifs.close(); ofstream ofs(myfile); if(ofs.fail()) { cout << "Error occurred!\n"; return 0; } cout << "Enter a line to store in the file: "; getline(cin, myline); ofs << myline << "\n"; cout << "\nThe information you entered was successfully saved!\n"; ofs.close(); cout << "\nDo you want to read the file? (y/n): "; cin >> ch; if (ch == 'y' || ch == 'Y') { ifstream ifs(myfile); while (getline(ifs, myline)) cout << myline; ifs.close(); } } cout << endl; return 0; }
The following snapshot shows the initial output produced by the above program:
Now type the name of the file, say "myfile.txt," and hit the ENTER key to create a file with the given name in the current directory. The current directory is the directory where the C++ source code is saved. The following snapshot shows the sample output after providing the stated input:
Because no errors were displayed, the file was successfully created, and it now has a line to store in it.For example, if I type "Hello there" as a line of text and hit the ENTER key, here is the output:
Now you can type "y" and hit the ENTER key to read the content of the file or anything else to skip or stop the execution of the program. The following sample run is given for your understanding.
More Examples
Here are the list of some more C++ examples, that you can go for:
- Read a File
- Write to File
- Read & Display File
- Copy File
- Merge two File
- List Files in Directory
- Delete File
- Encrypt and Decrypt Files
« Previous Tutorial Next Tutorial »