Error Handling in File I/O
Introduction
Handle file errors by checking open success, state flags, and using exceptions if needed.
Definition
File Error Handling: check open success and stream state.
C++ Code Example
#include
#include
using namespace std;
int main(){
ifstream f("missing.txt");
if(!f){ cerr<<"Cannot open file\n"; return 1; }
if(f.fail()){ cerr<<"Read error\n"; }
} Important Questions
Short Questions
- How to detect open failure?
- How to handle read errors?
- What is cerr?
- Should we close on error?
Long Questions
- Explain file error handling.
- Discuss checking stream state.
MCQ Practice
1. Open failure detected by:
- if(!f)
- if(f)
- always
- never
Answer: if(!f).
2. cerr is:
- Error output stream
- Input stream
- File stream
- None
Answer: Error output stream.
3. On failure, should:
- Handle and exit/close
- Ignore
- Continue
- None
Answer: Handle and exit/close.
4. fail() indicates:
- Logical failure
- Success
- EOF only
- Good
Answer: Logical failure.
5. Good practice:
- Check before use
- Ignore errors
- Assume success
- None
Answer: Check before use.
Quick Revision
- Check open success first.
- Use cerr for errors.