Skip to main content

Errors encountered during file operation

Short answer

Errors include opening nonexistent files, disk full, reading past end, stream not opened, invalid mode, and hardware failure. C++ stream state flags eof(), fail(), bad(), good() test these, and clear() resets them. Always check open success and read/write results.

Explain the different errors encountered during file operation.

Errors can occur during file operations, for example when opening a missing file or reading past the end. C++ records them in the stream state flags of ios, which can be tested with member functions.

Common error situations

  1. Opening a file for reading that does not exist.
  2. Opening a file with an invalid or non-existent name/path, or a write-protected file.
  3. Opening a file for writing when the disk is full or write permission is missing.
  4. Reading past the end of the file.
  5. Using a stream that has not been opened, or attempting an operation not allowed by the mode (for example, reading from an fstream opened only with ios::out).
  6. Hardware or disk failures during reading or writing, and unreadable data (reading text where a number is expected).
  7. Too many files open at once.

Error-state flags and functions

FunctionMeaning
eof()True when the end of file is reached (eofbit)
fail()True when an operation failed, e.g. invalid input or open failure (failbit/badbit)
bad()True on a serious, unrecoverable error (badbit)
good()True when there is no error (all bits clear)
clear()Resets the error flags

Example

#include <iostream>
#include <fstream>
using namespace std;
int main() {
    ifstream fin("missing.txt");
    if (fin.fail()) {                       // or: if (!fin)
        cout << "Cannot open file\n";
        return 1;
    }
    int x;
    while (fin >> x) cout << x << endl;
    if (fin.eof()) cout << "End of file reached\n";
    else if (fin.bad()) cout << "Fatal read error\n";
    fin.close();
    return 0;
}

Also check is_open() after opening, and always test the result of each read or write.

✓ Answer checked by Claude Opus 5.5 (high effort)

All Object Oriented Programming chapter 8 questions →