Loading lessons...
Basic File I/O
Basic File I/O
Behind the friendly fstream classes sit streams: a stream is a connection between your program and a data source. The same stream ideas power console and file work.
Opening modes
When you open a file you can say exactly what you plan to do with it:
in- open for reading.out- open for writing.trunc- delete the file's contents when opening.app- append new writes to the end of the file.
ofstream MyFile("data.txt", ios::app); // keep old data, add to the end
The default for ofstream is out plus trunc, so writing normally wipes the old contents.
Did the file open?
Before using a file, ask if it actually opened. A missing file, or a read without permission, would otherwise fail silently:
ifstream MyFile("data.txt");
if (MyFile.is_open()) {
// safe to read
} else {
cout << "Could not open the file";
}
is_open() returns true only when the file stream is connected to a real, opened file.
Reading line by line
The classic pattern reads every line and prints it:
string line;
while (getline(MyFile, line)) {
cout << line << "\n";
}
Each pass of the loop reads one whole line into line. At the end of the file, getline() returns false and the loop stops on its own.
Writing and closing
Writing mirrors cout with the insertion operator, and .close() releases the file:
ofstream Out("out.txt");
Out << "Hello file!";
Out.close();
TL;DR
- Open modes:
in,out,trunc,app. - The
ofstreamdefault isout | trunc- old contents are wiped. - Check success with
is_open()before reading or writing. getline(stream, line)reads one line at a time in a while loop.- Always
.close()the file when done.