C++ Lesson 31 โ€“ File /Handling | Dataplexa
Advanced C++ ยท Lesson 31

File Handling

Everything a program knows lives in memory โ€” and memory forgets the moment the program ends. A high score, a shopping list, a settings file: all gone when the window closes. Files fix that. A file is memory that survives: your program writes its data out to disk, and later โ€” tomorrow, next week, after a restart โ€” it reads the data back in again.

1. Why Files?

Think of memory as a whiteboard and a file as a notebook. The whiteboard is fast and easy, but someone wipes it at the end of the day. The notebook is slower to write in, but what you write stays. C++ treats files exactly like the console: you send text out with << and pull text in with >> โ€” only the destination changes from the screen to a file on disk.

Code story: A program writes one short note into a file called notes.txt, closes the file, then opens the same file for reading and prints the note back. Watch the two halves: the first half creates the file, the second half proves the note really survived.

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

int main() {
    ofstream out("notes.txt");
    out << "Hello, file!" << endl;
    out.close();

    ifstream in("notes.txt");
    string line;
    getline(in, line);
    cout << "From the file: " << line << endl;
    return 0;
}
From the file: Hello, file!

What just happened? ofstream out("notes.txt"); created the file and opened it for writing โ€” out << ... works just like cout << .... Then ifstream in("notes.txt"); opened the same file for reading, and getline(in, line) pulled the whole line back out. The file lands in the same folder as the program โ€” that folder is the program's working directory. And out.close(); matters: it makes sure the text is really written to disk before the file is closed.

2. The Three Stream Classes

All file work in C++ goes through three classes from the <fstream> header. Their names tell you their direction: o for output (out of the program, into the file), i for input (into the program, out of the file).

ClassUsed forOpens the file
ofstreamWriting (output)Creates the file, or erases it if it already exists.
ifstreamReading (input)Opens an existing file to read from.
fstreamBoth reading and writingDepends on the mode you pass.

3. Writing to a File โ€” ofstream

Writing is the easy direction. Open an ofstream with the file name, send text into it with << exactly as you would to cout, and close it. One warning: opening an existing file with a plain ofstream erases everything in it first. If you want to add to the end instead, open it with the append mode: ofstream out("scores.txt", ios::app);

Code story: A teacher saves three exam scores into scores.txt โ€” one name and one score per line. Watch that each line ends with endl: without it, all three scores would run together on one line and be much harder to read back.

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

int main() {
    ofstream out("scores.txt");
    out << "Ada 95" << endl;
    out << "Ben 82" << endl;
    out << "Cleo 88" << endl;
    out.close();
    cout << "3 scores saved." << endl;
    return 0;
}
3 scores saved.

What just happened? The three lines landed in scores.txt, one per line, and out.close(); flushed them to disk. If you ran this program a second time, the old scores would be erased first โ€” the plain ofstream always starts from an empty file. With ios::app instead, the second run would add three more lines underneath.

4. Reading from a File โ€” ifstream and getline

Reading is where beginners get bitten: the file might not exist. Always check that the open worked โ€” if (!in) is true when the file could not be opened. Then read line by line: getline(in, line) reads a whole line, spaces included, and returns false when the file runs out โ€” so a while loop around it reads the file to the end.

Code story: The program opens the scores.txt file from the last section and prints every line. Watch the guard at the top โ€” if the file is missing, the program says so and quits politely instead of reading garbage.

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

int main() {
    ifstream in("scores.txt");
    if (!in) {
        cout << "Could not open scores.txt" << endl;
        return 1;
    }
    string line;
    while (getline(in, line)) {
        cout << line << endl;
    }
    return 0;
}
Ada 95
Ben 82
Cleo 88

What just happened? Each round of the while loop pulled one line out of the file and printed it. When the file ran out of lines, getline returned false and the loop stopped by itself โ€” no counting lines, no guessing the file size. Use getline whenever a line can contain spaces; the >> operator stops at the first space, so it would split a name like Mary Jane in two.

5. Reading Numbers and Checking for Errors

When the file holds neat columns โ€” a name and a number, over and over โ€” the >> operator is the right tool: in >> name >> score reads one name and one score per round, and the loop condition fails the moment the file runs out or the data stops matching. Keep both guards in place: check the open, and let the loop condition do the end-of-file check for you.

Code story: The program reads the same scores.txt file, but this time it does maths on it โ€” it adds up the scores and counts the students, then prints the average. Watch the loop condition: in >> name >> score is the whole test โ€” it reads a pair and tells the loop whether it worked.

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

int main() {
    ifstream in("scores.txt");
    if (!in) {
        cout << "Could not open scores.txt" << endl;
        return 1;
    }
    string name;
    int score, total = 0, count = 0;
    while (in >> name >> score) {
        total += score;
        count++;
    }
    cout << "Students: " << count << endl;
    cout << "Average: " << total / count << endl;
    return 0;
}
Students: 3
Average: 88

What just happened? The three scores (95, 82, 88) add up to 265, and 265 / 3 is 88 with integer division โ€” the same Lesson 7 rule as always, so the average is rounded down. The loop read exactly 3 pairs and then stopped on its own when the file ended. If the file had contained a broken line, the loop would have stopped there instead โ€” which is why this pattern is safer than looping while !in.eof(), a check that only turns true AFTER a read has already failed.

Never loop on while (!in.eof()). That flag only turns on after a read fails, so the loop runs one extra time and processes the last line twice.

6. Common Mistakes with File Handling

MistakeWhat happensFix
Forgetting to check whether the file openedReads silently give nothing โ€” the program prints empty results.Check if (!in) right after opening.
Using >> to read a line with spaces in itThe line is split at the first space.Use getline(in, line) for whole lines.
Forgetting close() when writingText sits in a buffer and may never reach the disk.Always call close() โ€” or let the stream go out of scope.
Opening an ofstream without app and wiping the fileThe old content is erased before the first write.Pass ios::app when you want to add to the end.
Reading past the end of the fileThe last line is processed twice, or garbage values appear.Loop on the read itself: while (getline(...)) or while (in >> ...).

Practice โ€” File Handling

Try these on your own. Type each program, run it, and check the output matches what you expect.

  1. Write your name, age and favourite colour to a file called about.txt, one per line, then read the file back and print it.
  2. Write the numbers 1 to 10, one per line, into numbers.txt. Then read them back and print their sum.
  3. Open your about.txt in append mode and add a second line with your city. Read the file back and check both lines are there.
  4. Write a program that reads scores.txt and prints only the students who scored above 90.

Which class do you use to write to a file?


What does ofstream do to an existing file by default?


How do you read a whole line, spaces included, from a file?


Fill in the blanks โ€” type the missing word into the box.

To write to a file, open it with an .


To read a whole line from a file, use .


Always a file when you are done with it.


Up Next

Templates

Next, write once, use with any type โ€” templates.