SyntaxPilot
Courses/C++/Lesson 32
Video coming soonThis lesson’s video is being made

Start with the notes below; the video appears here as soon as it is on YouTube.

C++ · Lesson 32 of 40

File streams

queued

These are the notes for C++ episode 32. Everything a program keeps in variables disappears when it ends. This episode shows that happening, then builds up file handling step by step: writing with ofstream, reading with ifstream, why a file must be closed, checking that a file opened, reading whole lines with getline, appending with ios::app, the while (!in.eof()) trap, and reading records from a CSV file with stringstream. Every example below was compiled with g++ -O2 -std=c++17 main.cpp -o main (g++ 13.3, the same command as the SyntaxPilot compiler) and run; outputs are copied from those runs.

About the online compiler: every run gets a brand-new empty folder, so each demo writes its file and reads it back in the same run. On your own computer the file stays in the program's folder, and a program you run tomorrow can read it.

The problem: the booking app forgets

The train booking counter from episode 31 keeps its bookings in a vector:

#include <iostream>
#include <vector>
#include <string>
using namespace std;

int main() {
    vector<string> bookings;
    string name;
    while (cin >> name)
        bookings.push_back(name);
    cout << "Bookings: " << bookings.size() << endl;
    for (string b : bookings)
        cout << "  " << b << endl;
    return 0;
}

Day one, input Asha Ravi Meera:

Bookings: 3
  Asha
  Ravi
  Meera

Next morning the program starts again, with no new input:

Bookings: 0

Why: variables live in RAM, the computer's working memory. When a program ends, the operating system takes all of its memory back. Anything that must survive has to be written to the disk, in a file.

Step 1: whiteboard or register?

At the station In C++
The whiteboard: quick to write on, wiped every night variables in RAM: fast, gone when the program ends
The booking register on the shelf: still there tomorrow a file on disk: slower to reach, but it lasts
Open the register, write, close it; later open it and read file streams: ofstream writes, ifstream reads

A stream is a flow of characters. You already know two: cout (to the screen) and cin (from the keyboard). A file stream is the same idea connected to a file, from the header <fstream>:

Type Stands for Use
ofstream output file stream write to a file, with <<
ifstream input file stream read from a file, with >> or getline
fstream file stream read and write the same file (rarely needed)

Step 2: write a file, then read it back

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main() {
    ofstream out("bookings.txt");      // open a file for writing
    out << "Asha" << endl;
    out << "Ravi" << endl;
    out << "Meera" << endl;
    out.close();

    ifstream in("bookings.txt");       // open it for reading
    string name;
    while (in >> name)
        cout << "Saved: " << name << endl;
    return 0;
}

Output:

Saved: Asha
Saved: Ravi
Saved: Meera
  • ofstream out("bookings.txt"); opens (and creates, if needed) the file for writing.
  • out << ... works exactly like cout << ..., but the text goes into the file.
  • ifstream in("bookings.txt"); opens it for reading; in >> name works like cin >> name.
  • while (in >> name) keeps reading until a read fails (the end of the file).

Step 3: close the file (the buffer)

Forget close(), end lines with \n instead of endl, and read the file straight away:

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main() {
    ofstream out("bookings.txt");
    out << "Asha\n" << "Ravi\n" << "Meera\n";
    // forgot out.close()

    ifstream in("bookings.txt");
    string name;
    int count = 0;
    while (in >> name)
        count++;
    cout << "Bookings read: " << count << endl;
    return 0;
}

Output:

Bookings read: 0

Writing to the disk is slow, so an ofstream collects text in a buffer (a small waiting area in memory) and writes it out in one go, like a waiter who collects every order at a table before walking to the kitchen. The buffer is flushed (written to the file) when:

  • it is full,
  • you write endl (newline + flush) or call out.flush(),
  • the file is closed: out.close(), or the stream object is destroyed.

None of those happened, so the names were still in the buffer when we read. The neatest fix is a scope: the stream's destructor closes the file (RAII, episode 28).

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main() {
    {
        ofstream out("bookings.txt");
        out << "Asha\n" << "Ravi\n" << "Meera\n";
    }                                  // out is destroyed here: closed

    ifstream in("bookings.txt");
    string name;
    int count = 0;
    while (in >> name)
        count++;
    cout << "Bookings read: " << count << endl;
    return 0;
}

Output:

Bookings read: 3

Step 4: did the file open?

A typo in the file name:

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main() {
    ifstream in("booking.txt");        // the file is bookings.txt
    string line;
    while (getline(in, line))
        cout << "Passenger: " << line << endl;
    return 0;
}

Output: nothing at all (the compiler shows (no output)). A file that can't be opened does not throw an exception; the stream goes into a failed state and every later read quietly fails. Always check right after opening:

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main() {
    ifstream in("booking.txt");        // the file is bookings.txt
    if (!in) {
        cout << "Could not open booking.txt" << endl;
        return 1;
    }
    string line;
    while (getline(in, line))
        cout << "Passenger: " << line << endl;
    return 0;
}

Output:

Could not open booking.txt

!in is true when the stream failed. return 1 from main tells the operating system the program failed. Reasons a file won't open: it's missing, misspelled, in another folder, or you lack permission.

Step 5: whole lines with getline

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main() {
    ofstream out("bookings.txt");
    out << "Asha Rao" << endl;
    out << "Ravi Kumar" << endl;
    out.close();

    ifstream in("bookings.txt");
    string name;
    while (in >> name)
        cout << "Passenger: " << name << endl;
    return 0;
}

Output:

Passenger: Asha
Passenger: Rao
Passenger: Ravi
Passenger: Kumar

>> reads one word: it stops at every space (just like cin in episode 4). To read a whole line, spaces and all, use getline(stream, string):

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main() {
    ofstream out("bookings.txt");
    out << "Asha Rao" << endl;
    out << "Ravi Kumar" << endl;
    out.close();

    ifstream in("bookings.txt");
    string name;
    while (getline(in, name))
        cout << "Passenger: " << name << endl;
    return 0;
}

Output:

Passenger: Asha Rao
Passenger: Ravi Kumar

Step 6: append instead of wiping (ios::app)

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

void addBooking(string name) {
    ofstream out("bookings.txt");
    out << name << endl;
}

int main() {
    addBooking("Asha Rao");
    addBooking("Ravi Kumar");
    addBooking("Meera Iyer");

    ifstream in("bookings.txt");
    string line;
    while (getline(in, line))
        cout << "Passenger: " << line << endl;
    return 0;
}

Output:

Passenger: Meera Iyer

Opening an ofstream truncates the file: it wipes it clean first, like tearing every page out of the register. Each addBooking erased the one before. Open it in append mode to write at the end instead:

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

void addBooking(string name) {
    ofstream out("bookings.txt", ios::app);
    out << name << endl;
}

int main() {
    addBooking("Asha Rao");
    addBooking("Ravi Kumar");
    addBooking("Meera Iyer");

    ifstream in("bookings.txt");
    string line;
    while (getline(in, line))
        cout << "Passenger: " << line << endl;
    return 0;
}

Output:

Passenger: Asha Rao
Passenger: Ravi Kumar
Passenger: Meera Iyer
Open mode Meaning
(default for ofstream) ios::out: write, wiping the file first (ios::trunc)
ios::app append: every write goes to the end; old data is kept
ios::in read (default for ifstream)
ios::binary raw bytes, no newline translation (images, binary data)

Modes combine with |, e.g. fstream f("data.txt", ios::in | ios::out);.

Step 7: the while (!in.eof()) trap

#include <iostream>
#include <fstream>
using namespace std;

int main() {
    ofstream out("fares.txt");
    out << 120 << endl << 250 << endl << 80 << endl;
    out.close();

    ifstream in("fares.txt");
    int fare, total = 0;
    while (!in.eof()) {                // "until the end of the file"
        in >> fare;
        total += fare;
    }
    cout << "Total fare: " << total << endl;
    return 0;
}

Output:

Total fare: 530

The fares are 120 + 250 + 80 = 450, but the program says 530: 80 was counted twice. eof() becomes true only after a read has tried to go past the end. After reading 80 there's still a newline left, so eof() is false; the loop runs once more, in >> fare fails, fare still holds 80, and 80 is added again. Put the read in the condition instead: a failed read makes the condition false.

#include <iostream>
#include <fstream>
using namespace std;

int main() {
    ofstream out("fares.txt");
    out << 120 << endl << 250 << endl << 80 << endl;
    out.close();

    ifstream in("fares.txt");
    int fare, total = 0;
    while (in >> fare)                 // stops when a read fails
        total += fare;
    cout << "Total fare: " << total << endl;
    return 0;
}

Output:

Total fare: 450

Step 8: records in a file (CSV)

One booking per line, with commas between the parts: Asha Rao,34,Delhi. This is CSV, comma-separated values; Excel and Google Sheets open it directly. To read it:

  1. getline(in, line) gets one whole record.
  2. stringstream ss(line); (header <sstream>) turns that string into a stream of its own.
  3. getline(ss, field, ',') reads up to the next comma; the third argument is the delimiter (the character to stop at).
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
using namespace std;

int main() {
    ofstream out("bookings.csv");
    out << "Asha Rao,34,Delhi" << endl;
    out << "Ravi Kumar,67,Pune" << endl;
    out.close();

    ifstream in("bookings.csv");
    string line;
    while (getline(in, line)) {
        stringstream ss(line);
        string name, age, city;
        getline(ss, name, ',');
        getline(ss, age, ',');
        getline(ss, city, ',');
        int fare = stoi(age) >= 60 ? 300 : 500;
        cout << name << " to " << city << ": Rs " << fare << endl;
    }
    return 0;
}

Output:

Asha Rao to Delhi: Rs 500
Ravi Kumar to Pune: Rs 300

Ages come out as text, so stoi converts them. If a line held abc instead of an age, stoi would throw invalid_argument (episode 31): real file readers wrap each line in try/catch and skip broken lines.

Cheat sheet

Task Code
Write (wipes the file) ofstream out("f.txt"); out << x << endl;
Append ofstream out("f.txt", ios::app);
Read word by word ifstream in("f.txt"); while (in >> word) { ... }
Read line by line while (getline(in, line)) { ... }
Check it opened if (!in) { ... } (or if (!in.is_open()))
Close / flush out.close(); or let the stream leave its scope; out.flush();
Split a CSV line stringstream ss(line); getline(ss, field, ',');

Common mistakes

Mistake What happens (real output) Fix
Not checking that the file opened (no output): every read silently fails if (!in) { cout << "Could not open ..."; return 1; }
Reading before the writer is closed Bookings read: 0 out.close() or a { } scope
ofstream on a file you want to keep only the last record is left ofstream out("f.txt", ios::app);
while (!in.eof()) { in >> x; ... } Total fare: 530 (should be 450): the last value counted twice while (in >> x)
in >> name for names with spaces Asha Rao becomes two passengers getline(in, name)
Mixing in >> x then getline(in, line) the getline returns an empty line (the leftover newline) in >> ws; or in.ignore() before getline

None of these is a compiler error: they all compile and give wrong answers.

Mini project: a chai stall sales log

Each sale is appended to sales.csv as item,cups,price; then the file is read back and the money per item is totalled with a map (episode 23).

#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <map>
using namespace std;

void recordSale(const string& item, int cups, int price) {
    ofstream out("sales.csv", ios::app);          // keep earlier sales
    out << item << "," << cups << "," << price << endl;
}

int main() {
    recordSale("chai", 3, 15);
    recordSale("coffee", 1, 30);
    recordSale("chai", 2, 15);
    recordSale("samosa", 4, 20);

    ifstream in("sales.csv");
    if (!in) {
        cout << "Could not open sales.csv" << endl;
        return 1;
    }
    map<string, int> earned;
    string line;
    while (getline(in, line)) {
        stringstream ss(line);
        string item, cups, price;
        getline(ss, item, ',');
        getline(ss, cups, ',');
        getline(ss, price, ',');
        earned[item] += stoi(cups) * stoi(price);
    }
    int total = 0;
    for (auto p : earned) {
        cout << p.first << ": Rs " << p.second << endl;
        total += p.second;
    }
    cout << "Total: Rs " << total << endl;
    return 0;
}

Output:

chai: Rs 75
coffee: Rs 30
samosa: Rs 80
Total: Rs 185

On your own computer, run it twice and the totals double: the earlier sales are still in the file, because of ios::app.

Practice

  1. Save a to-do list (three tasks) to todo.txt, then print it back with numbers.
  2. Count the lines and words in a text file.
  3. Append each day's chai sales to sales.txt (the mini project above).
  4. Read students.csv (name,marks) and print the topper.
Solutions

Exercise 1:

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main() {
    {
        ofstream out("todo.txt");
        out << "buy milk" << endl << "pay electricity bill" << endl << "call Ravi" << endl;
    }
    ifstream in("todo.txt");
    if (!in) { cout << "Could not open todo.txt" << endl; return 1; }
    string task;
    int n = 1;
    while (getline(in, task))
        cout << n++ << ". " << task << endl;
    return 0;
}

Output:

1. buy milk
2. pay electricity bill
3. call Ravi

Exercise 2 (a stringstream over each line counts its words):

#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
using namespace std;

int main() {
    ofstream out("poem.txt");
    out << "chai in the morning" << endl;
    out << "samosa at four" << endl;
    out << "and one more chai" << endl;
    out.close();

    ifstream in("poem.txt");
    if (!in) { cout << "Could not open poem.txt" << endl; return 1; }
    int lines = 0, words = 0;
    string line, word;
    while (getline(in, line)) {
        lines++;
        stringstream ss(line);
        while (ss >> word) words++;
    }
    cout << "Lines: " << lines << ", words: " << words << endl;
    return 0;
}

Output:

Lines: 3, words: 11

Exercise 4:

#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
using namespace std;

int main() {
    ofstream out("students.csv");
    out << "Asha Rao,91" << endl;
    out << "Ravi Kumar,78" << endl;
    out << "Meera Iyer,95" << endl;
    out.close();

    ifstream in("students.csv");
    if (!in) { cout << "Could not open students.csv" << endl; return 1; }
    string line, topName;
    int topMarks = -1;
    while (getline(in, line)) {
        stringstream ss(line);
        string name, marks;
        getline(ss, name, ',');
        getline(ss, marks, ',');
        if (stoi(marks) > topMarks) {
            topMarks = stoi(marks);
            topName = name;
        }
    }
    cout << "Topper: " << topName << " with " << topMarks << endl;
    return 0;
}

Output:

Topper: Meera Iyer with 95

Quick quiz

What is in a.txt after this runs?

ofstream out("a.txt");
out << "chai" << endl;
out.close();
ofstream out2("a.txt");
out2 << "samosa" << endl;
out2.close();
// What does a.txt contain now?
Answer

samosa. The second ofstream opens a.txt without ios::app, so the file is wiped before samosa is written.

Interview questions

  1. Why might data written to a file seem to be missing? It's still in the stream's buffer; it reaches the disk on flush, endl, close() or when the stream is destroyed.
  2. What's wrong with while (!in.eof())? eof() is set only after a read fails, so the loop runs one extra time and processes stale data. Loop on the read: while (in >> x) or while (getline(in, line)).
  3. How do you append to a file? Open it with ios::app: ofstream out("f.txt", ios::app);.
  4. Difference between >> and getline? >> skips leading whitespace and reads one word; getline reads everything up to the newline (or a chosen delimiter).
  5. Does a failed ifstream open throw? No, by default it sets the stream's fail state. Check with if (!in) or is_open(). (You can ask for exceptions with in.exceptions(...).)
  6. What is RAII here? The stream closes its file in its destructor, so leaving the scope always closes it, even when an exception is thrown.
  7. Text vs binary mode? Text mode may translate newlines (on Windows \n becomes \r\n); ios::binary writes bytes exactly.

Glossary

Term Meaning, with an example
RAM The computer's working memory; variables live here and are lost when the program ends.
disk Long-term storage (SSD or hard disk); files stay here after the program ends and after a restart.
file A named block of data on the disk, e.g. bookings.txt.
stream A flow of characters you write to or read from: cout, cin, file streams.
<fstream> The header for file streams.
ofstream Output file stream: ofstream out("f.txt"); out << "Asha";
ifstream Input file stream: ifstream in("f.txt"); in >> name;
fstream A file stream that can both read and write.
buffer A waiting area in memory where written text collects before it goes to the disk.
flush Write the buffer out to the file: endl, out.flush(), close().
close() Flushes and closes the file: out.close();
scope A { } block; objects made in it are destroyed at the closing brace.
RAII Cleanup in destructors: an ofstream closes its file when destroyed (episode 28).
fail state A stream's "something went wrong" flag; !in is true and reads stop working.
is_open() True if the stream has a file open.
getline Reads a whole line into a string: getline(in, line); with a third argument, up to that character.
delimiter The character that separates parts, like , in CSV.
truncate Wipe a file's contents when opening it (the ofstream default).
ios::app Append mode: writes go to the end of the file.
open mode How a file is opened: ios::in, ios::out, ios::app, ios::binary, combined with |.
eof() "End of file": true only after a read has tried to go past the end.
CSV Comma-separated values: one record per line, fields separated by commas.
record One row of data, e.g. one booking: name, age, city.
field One part of a record, e.g. the age.
<sstream> / stringstream A stream over a string, used to split a line: stringstream ss(line);
stoi Converts text to an int: stoi("34") is 34.

Summary

  • Variables live in RAM and vanish when the program ends; files on disk last.
  • ofstream writes with <<, ifstream reads with >>, from <fstream>.
  • Text waits in a buffer: close the file (or leave its scope) before reading it back.
  • A failed open is silent: always check if (!in).
  • getline reads a whole line; ios::app appends instead of wiping.
  • Loop on the read, never on eof().
  • CSV lines split with stringstream and getline(ss, field, ',').

Next episode: our lines are getting long: vector<string>::iterator... Modern C++ lets the compiler do that typing for you. auto, range-for and structured bindings.