C++ streams (std::ifstream, std::ofstream) provide RAII file I/O—files close when streams destruct. Alternative: C fopen from C still works in C++.
Writing and reading
std::ofstream out("demo.txt");
out << "hello\n";
out.close();
std::ifstream in("demo.txt");
std::string line;
std::getline(in, line);
Always check is_open() or stream state after open operations.
Important interview questions and answers
- Q: RAII with streams?
A: Destructor closes the file—avoid leaks even when exceptions throw. - Q: Binary vs text mode?
A: Usestd::ios::binaryon Windows for byte-exact I/O; POSIX often treats them similarly.
Self-check
- Which class reads from files?
- Why check is_open()?
Pitfall: Forgetting to check is_open() leads to silent failures—always verify stream state after open.
Interview prep
- RAII with streams?
Stream destructors close files—cleanup happens even when exceptions throw.
- Check open failure?
Use
is_open()or test stream state—silent failures otherwise.