The std::ifstream and the std::ofstream are the two stream classes that read and write the files. An std::ofstream is opened with a filename and everything that you write to it goes into that file. An std::ifstream reads a file back. The most important habit with both of them is to check that the file opened, because the failure is silent otherwise.
This is the first lesson in the Files and Practical IO module, and the next lesson in this module is about "What Do Binary Files Change About IO?".
Writing a file
#include <fstream>
#include <iostream>
#include <string>
int main() {
std::ofstream file("members.txt");
if (!file) {
std::cerr << "could not open members.txt for writing\n";
return 1;
}
file << "m-001|Alice|2024\n";
file << "m-002|Bob|2025\n";
file << "m-003|Carol|2026\n";
file.close();
std::cout << "three records written\n";
return 0;
}The output confirms the write.
three records writtenReading a file
The most common pattern is to read a line at a time with the std::getline until the stream runs out.
#include <fstream>
#include <iostream>
#include <string>
int main() {
std::ifstream file("members.txt");
if (!file) {
std::cerr << "could not open members.txt for reading\n";
return 1;
}
std::string line;
int count = 0;
while (std::getline(file, line)) {
++count;
std::cout << "line " << count << ": " << line << '\n';
}
std::cout << "read " << count << " lines\n";
return 0;
}The output shows the three records read back.
line 1: m-001|Alice|2024
line 2: m-002|Bob|2025
line 3: m-003|Carol|2026
read 3 linesThe stream state
Every stream carries a set of flags. The std::ifstream::good() is true when none of them is set, and it is the check to use after opening a file.
#include <fstream>
#include <iostream>
#include <string>
int main() {
std::ifstream file("members.txt");
if (!file.good()) {
std::cerr << "the stream is not in a good state\n";
return 1;
}
std::string line;
std::getline(file, line);
std::cout << "first line: " << line << '\n';
std::cout << "good: " << file.good() << '\n';
std::cout << "eof: " << file.eof() << '\n';
std::cout << "fail: " << file.fail() << '\n';
std::cout << "bad: " << file.bad() << '\n';
return 0;
}The output shows the state of the stream after one line has been read.
first line: m-001|Alice|2024
good: 1
eof: 0
fail: 0
bad: 0Open modes
The app mode is what you want for a log file, and getting it wrong is how a log gets emptied on every run.
#include <fstream>
#include <iostream>
int main() {
{
std::ofstream file("members.txt", std::ios::app);
if (!file) {
std::cerr << "could not open for appending\n";
return 1;
}
file << "m-004|Dave|2026\n";
}
std::ifstream file("members.txt");
std::string line;
int count = 0;
while (std::getline(file, line)) {
++count;
}
std::cout << "records now: " << count << '\n';
return 0;
}The output shows the record being appended rather than replacing the file.
records now: 4Reading and writing in one go
The std::fstream does both, and the seekg and the seekp functions move the position.
#include <fstream>
#include <iostream>
#include <string>
int main() {
std::ofstream create("positions.txt");
create << "alpha\nbravo\ncharlie\n";
create.close();
std::fstream file("positions.txt", std::ios::in | std::ios::out);
if (!file) {
std::cerr << "could not open for reading and writing\n";
return 1;
}
file.seekg(0, std::ios::end);
std::cout << "size: " << file.tellg() << " bytes\n";
file.seekg(0, std::ios::beg);
std::string line;
std::getline(file, line);
std::cout << "first: " << line << '\n';
file.close();
return 0;
}The output shows the file size and the first line read back.
size: 20 bytes
first: alphaBinary mode and line endings
Opening with the std::ios::binary turns the translation off, and it is the correct choice whenever the file format is defined in the bytes and not in the lines.
#include <fstream>
#include <iostream>
int main() {
std::ofstream file("raw.bin", std::ios::binary);
if (!file) {
std::cerr << "could not open raw.bin\n";
return 1;
}
const char bytes[] = {'a', 'b', '\n', 'c'};
file.write(bytes, 4);
file.close();
std::ifstream check("raw.bin", std::ios::binary);
char buffer[4] = {0};
check.read(buffer, 4);
std::cout << "bytes read: " << check.gcount() << '\n';
std::cout << "third byte: " << static_cast<int>(buffer[2]) << '\n';
return 0;
}The output shows all four bytes read back, with the newline preserved exactly as it was written.
bytes read: 4
third byte: 10Common file errors
- The file does not exist and you were reading it. The check on the stream catches it.
- The directory does not exist and you were writing to it. The same check catches it.
- The file is open in another program that forbids the sharing. The write fails and the stream is in the failed state.
- You ran out of the disk space. The write fails part way through, so you should check the stream after the writes as well as after the open.
Reading numbers from a file
Reading the formatted values from a file uses the same extraction operators as reading from the keyboard, because an std::ifstream is an std::istream.
#include <fstream>
#include <iostream>
#include <string>
int main() {
{
std::ofstream file("readings.txt");
file << "42 91 12\n7 5 3\n";
}
std::ifstream file("readings.txt");
if (!file) {
std::cerr << "could not open readings.txt\n";
return 1;
}
int first = 0;
int second = 0;
int third = 0;
int rows = 0;
while (file >> first >> second >> third) {
++rows;
std::cout << "row " << rows << ": " << first << ' ' << second << ' ' << third << '\n';
}
std::cout << "rows read: " << rows << '\n';
return 0;
}The output shows the two rows of three values each.
row 1: 42 91 12
row 2: 7 5 3
rows read: 2Quick reference
- The
std::ofstreamwrites and thestd::ifstreamreads, and thestd::fstreamdoes both. - You always check the stream after the open, because the failure is silent otherwise.
- The
std::getlinereads a line and it keeps the spaces inside it. - The app mode appends to the file, and the default mode replaces it.
- The seek functions move the position, and the tell functions report it.
- The binary mode turns the translation off, and it is for the formats that are defined in the bytes.
Try it yourself: write three records to a file, read them back, and count the lines. Then read the same file with the extraction operator instead of the getline, and see what happens when a line has a different number of fields. Finally, open it in the append mode and check that the earlier records are still there.