Reading and Writing Files

So far, everything disappears when the program ends. To keep data, save it in a file. The tools are in <fstream>:

  • ofstream – output file stream: write to a file (like cout).
  • ifstream – input file stream: read from a file (like cin).

Writing and reading back

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

int main() {
    ofstream out("notes.txt");
    out << "Buy milk\n";
    out << "Call Sam\n";
    out << "Learn C++\n";
    out.close();

    ifstream in("notes.txt");
    string line;
    int number = 1;
    while (getline(in, line)) {
        cout << number << ". " << line << "\n";
        number++;
    }
    return 0;
}

Run it on a real Linux machine (press Try it to open the practice terminal)

g++ main.cpp -o main && ./main

while (getline(in, line)) reads one line each round and stops at the end of the file.

Tip: The small WebAssembly compiler in the inline editor has no real disk, so these file examples use the practice terminal instead: a real Debian machine running in your browser. Press Try it under a program to compile it with g++ and run it there, with real files you can list with ls and read with cat.

Checking that a file opened

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

int main() {
    ifstream in("does-not-exist.txt");
    if (!in) {
        cout << "Could not open the file\n";
        return 1;
    }
    cout << "Opened!\n";
    return 0;
}

Run it on a real Linux machine (press Try it to open the practice terminal)

g++ main.cpp -o main && ./main

Common mistake: Not checking if the file opened. If it didn't, every read quietly fails and you get empty or wrong results.

Reading numbers and adding to a file

>> works on files just like on cin. Open a file with ios::app to append (add to the end) instead of replacing what's there:

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

int main() {
    {
        ofstream out("scores.txt");
        out << 10 << " " << 25 << "\n";
    }                                         // file closes here (RAII!)
    {
        ofstream more("scores.txt", ios::app);
        more << 40 << "\n";
    }
    ifstream in("scores.txt");
    int x, total = 0, count = 0;
    while (in >> x) {
        total += x;
        count++;
    }
    cout << count << " scores, total " << total << "\n";
    return 0;
}

Run it on a real Linux machine (press Try it to open the practice terminal)

g++ main.cpp -o main && ./main
HOME LABS COMMUNITY DASHBOARD
Practice terminal Starting…