File Handling in C++
Save your program's data and read it back later
std::ofstream (output — writing) and std::ifstream (input — reading).
- include the
<fstream>header and open a file, - write text and numbers to a file with
std::ofstream, - read data back with
std::ifstreamusing>>andgetline, - check that a file opened, close it, and add to it without erasing.
1. Why do we need files?
Think of your program's memory (RAM) like a whiteboard. It is fast and handy while you work, but when the program ends, the whiteboard is wiped clean. A file on the disk is like a notebook: what you write there stays until you change it, even after the computer is turned off.
Files let a game remember your high score, a to-do app keep your tasks, and a program share data with other programs. This ability to keep data after the program closes is called persistence.
2. The fstream toolbox
All file tools live in one header. Add this line at the top of your program:
#include <fstream>
It gives you three stream types. The easy way to remember them is from the point of view of your program:
| Type | What it does | Direction |
|---|---|---|
std::ofstream | output file stream — writes data to a file | program → file |
std::ifstream | input file stream — reads data from a file | file → program |
std::fstream | can do both reading and writing | both ways |
std::cout and std::cin that you already know — you use << to write and >> to read. A file stream is simply cout/cin pointed at a file instead of the screen.