- 2069 Chaitra · 5 marks
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
- Opening a file for reading that does not exist.
- Opening a file with an invalid or non-existent name/path, or a write-protected file.
- Opening a file for writing when the disk is full or write permission is missing.
- Reading past the end of the file.
- Using a stream that has not been opened, or attempting an operation not allowed by the mode (for example, reading from an
fstreamopened only withios::out). - Hardware or disk failures during reading or writing, and unreadable data (reading text where a number is expected).
- Too many files open at once.
Error-state flags and functions
| Function | Meaning |
|---|---|
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)
Related questions
- File I/O operations, errors, random access · Computer Programming, chapter 10
- EDM operation principles and errors · Surveying I, chapter 2 · asked 2×
- Face observation errors; optical theodolite · Surveying I, chapter 7 · asked 2×
- SUN NFS architecture and operation · Distributed System, chapter 2 · asked 3×