C++ Tutorial: File I/O
Read and write files with fstream, ifstream, ofstream — text mode, binary mode, and stream state checking.
Files: data that outlives your program
C++ file I/O uses streams — the same interface as `cin` and `cout`. `ifstream` reads, `ofstream` writes, `fstream` does both.
RAII applies here too: the destructor closes the file automatically when the stream goes out of scope.
What you'll learn in this C++ file i/o tutorial
This interactive C++ tutorial has 6 hands-on exercises. Estimated time: 16 minutes.
- Write to a file — `ofstream` opens a file for writing. Use `<<` just like `cout`:
- Read from a file — line by line — `ifstream` reads from a file. `getline(file, line)` reads one line.
- Read word by word with >> — `>>` on ifstream reads one whitespace-separated token at a time — like `cin`.
- Check stream state — Always check if a file opened successfully:
- filesystem — modern path handling — `<filesystem>` (C++17) provides cross-platform file system operations:
- Build a log file system — No starter code.
C++ File I/O concepts covered
- Files: data that outlives your program