Thuta Learning
C++
AdvancedProgrammingBeginner

File I/O

C++Lesson 2530 min

What you'll walk away with

  • Open a file for writing or appending with std::ofstream and check is_open() before using it
  • Read a file line by line with while (std::getline(in, line)) and explain why while (!in.eof()) is wrong
  • Explain how buffering and RAII decide when text actually reaches the disk
  • Build paths with std::filesystem and parse each line with std::istringstream

Explain it simply

File I/O in plain language

A program's variables vanish the moment it exits. A file is how data survives until the next run: settings, a high-score table, a log of what happened overnight. C++ treats a file just like the screen and the keyboard, as a stream of characters. You already write to std::cout with <<; an std::ofstream is the same idea, except the characters land in a file.

Reading works the other way round. An std::ifstream hands you characters from a file, and std::getline pulls them out one line at a time, the way you would read a shopping list from top to bottom. Both classes live in the <fstream> header.

Problem → Why → Solution

The problem: where did the text I just wrote go?

You write a note to a file and, a few lines later in the same function, open it again to show it to the user. The program prints nothing. No error, no crash, and after the program ends the file is on disk with the right text in it. What went wrong is timing: when you read, the text was still waiting in the writer's memory.

read_too_early.cpp
#include <fstream>
#include <iostream>
#include <string>

int main() {
    std::ofstream out("notes.txt");
    out << "remember the milk\n";

    std::ifstream in("notes.txt");       // out is still open: text is in its buffer
    std::string line;
    if (std::getline(in, line)) {
        std::cout << "read: " << line << '\n';
    } else {
        std::cout << "nothing to read yet\n";   // this branch runs
    }
}

Why the read came back empty

An std::ofstream does not send every << straight to the disk. It collects characters in a buffer and writes them in larger pieces, because each trip to the operating system is slow. The buffer is flushed when it fills up, when you call flush() or close(), or when the stream object is destroyed. Until then, a second stream that opens the same file sees only what is on disk, which here is still nothing.

Core concept: open, check, transfer, close

<fstream> gives you three classes: std::ofstream for writing, std::ifstream for reading and std::fstream for both. Passing a path to the constructor opens the file. Opening can fail: the folder is missing, you lack permission, the name is misspelled. Crucially, a stream does not throw by default; it sets a fail flag and silently ignores every later operation. That is why you check is_open() or if (!out) immediately after opening.

How you open itWhat it does
std::ofstream out(path)creates the file, or empties an existing one
std::ofstream out(path, std::ios::app)keeps the content; every write goes to the end
std::ifstream in(path)opens for reading; fails if the file is missing
... | std::ios::binaryno newline translation; bytes stay exactly as written

For reading, the standard shape is while (std::getline(in, line)). getline returns the stream itself, and a stream converts to false once a read has failed, so the loop body runs only for lines that were really read. The >> operator reads one whitespace-separated word or number; getline reads a whole line up to the '\n'.

A stream carries four state flags: good, eof, fail and bad. eof is set only after a read has tried to go past the end, so it reports the past rather than predicting the future.

File streams follow RAII: the destructor flushes the buffer and closes the file. Wrapping the writer in a small { } scope is therefore the cleanest way to guarantee the data is on disk before a reader opens it. Build paths with std::filesystem::path, and remember that a relative path such as "data.txt" is resolved against the current working directory the program was started from, not the folder that holds your .cpp file.

A file stream is a buffered pipe
  1. Open: constructor connects to a path
  2. Check: is_open() before any use
  3. Transfer: << or getline via a buffer
  4. Close: destructor flushes the buffer

Data you wrote is only guaranteed to be on disk after a flush, a close, or the end of the stream's scope.

General pattern

cpp
std::ofstream out(path);            // or std::ofstream out(path, std::ios::app);
if (!out.is_open()) { /* report and stop */ }
out << value << '\n';
out.close();                        // or simply let the scope end

std::ifstream in(path);
if (!in.is_open()) { /* report and stop */ }
std::string line;
while (std::getline(in, line)) {
    // use line
}

Open, check, transfer, close, in that order for both directions. The writer must be closed or out of scope before a reader opens the same file, and the read loop's condition is the read itself.

Worked example: write a score file, read it back, clean up

The program creates a uniquely named file in the system's temporary folder, writes three records, reads them back with line numbers, and deletes the file. Notice the extra pair of braces around the writer: they end the ofstream's life, so it is flushed and closed before the reader opens the same path. Only a file name is ever printed, never the full path, because the temporary folder differs on every machine.

score_file.cpp
#include <chrono>
#include <filesystem>
#include <fstream>
#include <iostream>
#include <string>

namespace fs = std::filesystem;

int main() {
    auto stamp = std::chrono::steady_clock::now().time_since_epoch().count();
    fs::path path = fs::temp_directory_path() /
                    ("scores-" + std::to_string(stamp) + ".txt");

    {
        std::ofstream out(path);                 // creates or truncates the file
        if (!out.is_open()) {
            std::cerr << "cannot create " << path.filename() << '\n';
            return 1;
        }
        out << "Aye 82\n";
        out << "Ko 91\n";
        out << "Su 77\n";
    }                                            // out is flushed and closed here

    std::ifstream in(path);
    if (!in.is_open()) {
        std::cerr << "cannot open " << path.filename() << '\n';
        return 1;
    }

    std::string line;
    int lineNumber = 0;
    while (std::getline(in, line)) {             // stops at end of file
        ++lineNumber;
        std::cout << lineNumber << ": " << line << '\n';
    }
    in.close();

    std::cout << "lines read: " << lineNumber << '\n';
    std::cout << "removed: " << std::boolalpha << fs::remove(path) << '\n';
}

Code breakdown

  1. A unique path in the temp folderfs::path path = fs::temp_directory_path() /

    temp_directory_path() returns the operating system's scratch folder, and operator/ joins the parts with the right separator. The clock's tick count in the name keeps two runs from colliding.

  2. Open and check at onceif (!out.is_open()) {

    The constructor has already tried to open the file; this line asks whether it worked. On failure the program writes a message with the file name to std::cerr and returns 1, so a broken stream is never used.

  3. The scope closes the writerstd::ofstream out(path);

    out is declared inside a { } block, so its destructor runs at the closing brace and all three buffered lines reach the disk. It uses the default mode, so an existing file would be emptied first.

  4. The read is the loop conditionwhile (std::getline(in, line)) {

    When a line is read, the body runs. The fourth getline hits the end of the file, the stream turns false and the loop stops, so the count is exactly 3.

  5. Clean up after yourselffs::remove(path)

    remove returns true when it actually deleted a file, so the cleanup is checked too. The reader was closed with in.close() first, because Windows refuses to delete a file that is still open.

You should see
1: Aye 82
2: Ko 91
3: Su 77
lines read: 3
removed: true

Parsing records and surviving bad lines

Real files carry several fields per line, and sooner or later one line is broken. The robust shape is to read the whole line with getline, wrap it in an std::istringstream, and pull the fields out with >>. When parsing fails, only that line's little string stream is affected; the file stream itself is still good and the next line can be read.

parse_marks.cpp
#include <chrono>
#include <filesystem>
#include <fstream>
#include <iostream>
#include <sstream>
#include <string>

namespace fs = std::filesystem;

int main() {
    auto stamp = std::chrono::steady_clock::now().time_since_epoch().count();
    fs::path path = fs::temp_directory_path() /
                    ("marks-" + std::to_string(stamp) + ".txt");
    {
        std::ofstream out(path);
        if (!out.is_open()) return 1;
        out << "Aye 82\nKo ninety\nSu 77\n";
    }

    std::ifstream in(path);
    if (!in.is_open()) return 1;
    std::string line;
    int total = 0, valid = 0, lineNo = 0;
    while (std::getline(in, line)) {
        ++lineNo;
        std::istringstream fields(line);         // parse one line at a time
        std::string name;
        int score = 0;
        if (fields >> name >> score) {
            total += score;
            ++valid;
        } else {
            std::cout << "line " << lineNo << " skipped: " << line << '\n';
        }
    }
    in.close();
    fs::remove(path);
    std::cout << valid << " valid records, total " << total << '\n';
}

This prints "line 2 skipped: Ko ninety" and then "2 valid records, total 159". The word "ninety" cannot be read as an int, so fields >> name >> score is false and the program carries on. For comma-separated CSV, replace >> with std::getline(fields, cell, ',') to split one cell at a time.

In real projects

File I/O in real projects

Even applications backed by a database still touch plain text files everywhere. The patterns in this lesson carry over directly to jobs like these:

  • Configuration: read key=value lines at startup and fall back to defaults when the file is missing. A missing file may simply mean a first run, so the is_open() result is handled on purpose rather than treated as a crash.
  • Log files: open with std::ios::app so every run adds lines. Services that flush after important events keep their last messages even when they crash.
  • CSV import and export: hand reports to spreadsheets and read data such as bank statements back in. Parsing line by line means one broken row does not stop the whole import.
  • Save files: games and editors write the new file under a temporary name, then replace the old one with std::filesystem::rename, so a power cut mid-write never destroys the previous save.

Common mistakes

Common mistakes with file I/O

Looping on while (!in.eof())

Reading a file holding "Aye 82" and "Ko 91" with while (!in.eof()) { in >> name >> score; ... } prints Ko 91 twice. After the second record eof is not set yet, so the loop runs once more, the read fails, and the body still uses the old values. Put the read in the condition: while (in >> name >> score).

Never checking that the file opened

When an ofstream fails to open, every later << is skipped without a sound and the program may happily report "saved". Check is_open() right after opening and print a message that names the file.

Mixing >> with getline

in >> count reads the number but leaves the '\n' behind, so the next getline returns an empty string at once. Skip the whitespace first with std::getline(in >> std::ws, name), or read every line with getline and parse it with an istringstream.

Assuming a relative path points next to the .cpp file

"data.txt" is looked up in the current working directory, which in many IDEs is the build folder. If the program works from a terminal but fails when started from the IDE, this is usually why.

Best practices

Best practices

  • Keep each stream in the smallest scope that needs it; its destructor flushes and closes for you.
  • Show path.filename() in error messages rather than the full path, so logs do not leak the user's folder layout.
  • Build paths with std::filesystem::path and operator/ instead of gluing strings with "/" or "\\".
  • Write important files under a temporary name and rename them into place, and delete test files when you are done.

Mini challenge

Mini challenge: an append-only deploy log

Write two helpers for a log file. appendLog adds one line to the end without erasing what is already there, and countLines reports how many lines the file holds plus the last one. Call appendLog three times, print the count and the last line, then delete the file and show that countLines reports the failure.

  • appendLog(path, message) opens with std::ios::app, checks is_open() and returns false on failure
  • countLines(path, lastLine) returns -1 when the file cannot be opened
  • Build the path with std::filesystem::temp_directory_path() and a unique name; never print the full path
  • Remove the file at the end
deploy_log.cpp
#include <chrono>
#include <filesystem>
#include <fstream>
#include <iostream>
#include <string>

namespace fs = std::filesystem;

bool appendLog(const fs::path& path, const std::string& message) {
    // TODO: open in append mode, check it, write message plus a newline
    return false;
}

int countLines(const fs::path& path, std::string& lastLine) {
    // TODO: return -1 when the file cannot be opened
    // TODO: read with std::getline, count lines, remember the last one
    return 0;
}

int main() {
    // TODO: build a unique path inside fs::temp_directory_path()
    // TODO: append "build started", "tests passed", "deploy finished"
    // TODO: print the line count and the last line
    // TODO: remove the file, then call countLines again
}

Expected: It prints lines after 3 appends: 3, last line: deploy finished and after remove: -1. Running it again still gives 3, because each run uses a new file name.

Show hint

std::ofstream log(path, std::ios::app) never truncates. In countLines, an ifstream on a missing file simply fails to open, so is_open() is your -1 check; inside the loop, overwrite lastLine on every pass.

Show solution
deploy_log.cpp
#include <chrono>
#include <filesystem>
#include <fstream>
#include <iostream>
#include <string>

namespace fs = std::filesystem;

bool appendLog(const fs::path& path, const std::string& message) {
    std::ofstream log(path, std::ios::app);      // append, never truncate
    if (!log.is_open()) return false;
    log << message << '\n';
    return static_cast<bool>(log);               // false if the write failed
}

int countLines(const fs::path& path, std::string& lastLine) {
    std::ifstream in(path);
    if (!in.is_open()) return -1;                // -1 means "could not open"
    int count = 0;
    std::string line;
    while (std::getline(in, line)) {
        ++count;
        lastLine = line;
    }
    return count;
}

int main() {
    auto stamp = std::chrono::steady_clock::now().time_since_epoch().count();
    fs::path path = fs::temp_directory_path() /
                    ("deploy-" + std::to_string(stamp) + ".log");

    for (const char* step : {"build started", "tests passed", "deploy finished"}) {
        if (!appendLog(path, step)) {
            std::cerr << "cannot write " << path.filename() << '\n';
            return 1;
        }
    }

    std::string last;
    std::cout << "lines after 3 appends: " << countLines(path, last) << '\n';
    std::cout << "last line: " << last << '\n';

    fs::remove(path);
    std::cout << "after remove: " << countLines(path, last) << '\n';
}

Quick quiz 1 / 3

A file holds the two lines "Aye 82" and "Ko 91". What does while (!in.eof()) { in >> name >> score; std::cout << name << ' ' << score << '\n'; } print?

Quick quiz 2 / 3

In the program from the problem section, which change lets the reader see the text?

Quick quiz 3 / 3

Each run should add lines to history.txt without losing earlier runs. Which line opens it correctly?

What to remember

  • std::ofstream writes, std::ifstream reads, and every open is checked with is_open(), because streams do not throw by default.
  • A plain ofstream empties the file; use std::ios::app to add to the end.
  • while (std::getline(in, line)) is the correct read loop; eof() only reports what already happened.
  • Written data is only guaranteed on disk after a flush, close or end of scope, so wrap the writer in { }.
  • Build paths with std::filesystem and remember that relative paths follow the working directory.

The Current ISO C++ Standard (C++23) — Standard C++ Foundation

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

File I/O | Thuta Learning