Modern C++ • C++20 baseline
Files, Streams, and the Filesystem Library
Use RAII streams for text files and check stream state after reading and writing.
C++ streams manage file resources through object lifetime. A stream can fail to open, fail during conversion, or encounter an error while reading. The filesystem library offers path manipulation but does not remove the need to handle permissions, missing files, and platform-specific path rules.
Key points
- Check a stream after opening and after operations whose success matters.
- Use std::filesystem::path rather than concatenating path strings manually.
Example
#include <fstream>
#include <stdexcept>
#include <string>
std::string read_first_line(const std::string& path) {
std::ifstream input(path);
if (!input) {
throw std::runtime_error("unable to open file");
}
std::string line;
if (!std::getline(input, line) && !input.eof()) {
throw std::runtime_error("error reading file");
}
return line;
}
What to expect
Returns the first line, or an empty string for an empty file; reports an open/read failure.
Practice exercise
Extend the reader to process every line and report a failure that occurs after several successful reads.
Key idea: Streams simplify resource lifetime, but the program must still inspect their state.