Files

Files in C++: To use a paper file you pull the drawer open, read or write, and push it shut.

The Analogy: The Filing Cabinet Drawer

To use a paper file you pull the drawer open, read or write, and push it shut. Leave drawers hanging open all afternoon and eventually you cannot walk through the room; forget to push one shut before the cleaners come and your last page never makes it in.

C++ file streams behave the same way, with one enormous convenience: the drawer shuts itself. An std::ifstream opens in its constructor and closes in its destructor, so the moment it goes out of scope — normally, by return, or because an exception was thrown — the file is closed and buffered writes are flushed. You almost never call close() yourself.

The other half of the job is doubt. A file might not exist, might be unreadable, might contain a line you cannot parse. File code that does not check is file code that silently loses data.


Syntax or Core Structure

Three types from <fstream>: std::ofstream to write, std::ifstream to read, std::fstream for both.

#include <iostream>
#include <fstream>
#include <string>

int main() {
    // --- Writing. Creates the file, or truncates an existing one.
    {
        std::ofstream out("scores.txt");
        if (!out) {                                 // always check
            std::cerr << "cannot open scores.txt for writing\n";
            return 1;
        }
        out << "Ada 91\n";
        out << "Grace 88\n";
        out << "Alan " << 95 << "\n";               // streams like std::cout
    }                                               // closed and flushed here

    // --- Appending: add to the end instead of replacing.
    {
        std::ofstream out("scores.txt", std::ios::app);
        out << "Edsger 79\n";
    }

    // --- Reading line by line.
    std::ifstream in("scores.txt");
    if (!in) {
        std::cerr << "cannot open scores.txt for reading\n";
        return 1;
    }

    std::string line;
    while (std::getline(in, line)) {                // the correct read loop
        std::cout << "[" << line << "]\n";
    }

    // --- Reading formatted fields instead.
    in.clear();                                     // reset the end-of-file flag
    in.seekg(0);                                    // rewind
    std::string name;
    int score = 0;
    while (in >> name >> score) {
        std::cout << name << " scored " << score << "\n";
    }
    return 0;
}

The braces around the writing blocks are deliberate: they end the stream's scope, which closes the file before the next section opens it again.


Technical Depth: Modes, States and Failure

Open modes

Combine them with |:

ModeMeaning
std::ios::inRead (default for ifstream)
std::ios::outWrite, truncating (default for ofstream)
std::ios::appEvery write goes to the end
std::ios::ateStart at the end, but you may seek back
std::ios::truncDiscard existing contents
std::ios::binaryNo newline translation
std::ofstream log("app.log", std::ios::app);                    // append
std::fstream db("data.bin", std::ios::in | std::ios::out | std::ios::binary);

Note that std::ofstream out("x.txt"); destroys the existing contents. Opening a log file without std::ios::app is how a day's logs disappear.

The four stream state bits

BitSet whenTest
goodbitEverything is finein.good()
eofbitA read hit end of filein.eof()
failbitA read failed to convert, or open failedin.fail()
badbitThe stream is unusablein.bad()

A stream converts to bool as "neither fail nor bad", which is why if (!in) and while (std::getline(in, line)) both work. Once failbit or eofbit is set, all further reads do nothing until you call in.clear().

Never loop on eof()

while (!in.eof()) {                 // WRONG
    std::getline(in, line);
    process(line);                  // processes the last line twice
}

eofbit is set by the read that hits the end, not before it, so the final iteration processes a line that was never read. Put the read in the condition instead:

while (std::getline(in, line)) { process(line); }

getline versus >>

>>std::getline
Stops atAny whitespaceThe newline (or a delimiter you give)
Leading whitespaceSkippedKept
Leaves the newline in the bufferYesNo
Good forNumbers, single wordsWhole lines, text with spaces

Mixing them causes the classic bug: in >> n leaves the newline behind, so the next getline returns an empty string. Fix it with in.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); after the >>.

Parse a line at a time with istringstream

The robust pattern for structured text: read whole lines, then parse each line separately, so one malformed row cannot desynchronise the rest of the file.

#include <sstream>

std::string line;
while (std::getline(in, line)) {
    std::istringstream fields(line);
    std::string name;
    int score = 0;
    if (!(fields >> name >> score)) { continue; }        // skip this row only
    // ...
}

For comma-separated data, std::getline takes a delimiter: std::getline(fields, cell, ',').

Reading a whole file at once

#include <sstream>

std::ifstream in("notes.txt");
std::ostringstream buffer;
buffer << in.rdbuf();                       // whole file in one go
const std::string text = buffer.str();

Text versus binary

In text mode on Windows, "\n" written to a file becomes CR-LF and is translated back on reading. That is convenient for text and fatal for anything else — a byte 0x0A inside an image would be corrupted. Always pass std::ios::binary for non-text data, and use read/write rather than <<:

struct Record { int id; double value; };

std::ofstream out("data.bin", std::ios::binary);
Record r{7, 3.5};
out.write(reinterpret_cast<const char*>(&r), sizeof(r));

std::ifstream in("data.bin", std::ios::binary);
Record back{};
in.read(reinterpret_cast<char*>(&back), sizeof(back));

This only works for trivially copyable types, and the file is not portable across machines with different padding or endianness. A std::string member cannot be written this way — you would be writing a pointer.

Position and size

in.seekg(0, std::ios::end);
const std::streamsize bytes = in.tellg();       // size in bytes
in.seekg(0, std::ios::beg);                     // back to the start

seekg/tellg are for reading, seekp/tellp for writing.

Flushing

Writes are buffered. std::endl writes a newline and flushes, which is why it is slower than "\n" in a loop. Flush deliberately when it matters — a crash log — and use "\n" everywhere else. Closing the stream, including by destruction, always flushes.

std::filesystem (C++17)

Questions about files, as opposed to their contents, belong to <filesystem>:

#include <filesystem>
namespace fs = std::filesystem;

if (fs::exists("scores.txt")) {
    std::cout << fs::file_size("scores.txt") << " bytes\n";
}
fs::create_directories("out/reports");
for (const auto& entry : fs::directory_iterator(".")) {
    std::cout << entry.path().filename().string() << "\n";
}

Do not check exists() and then open — between the two calls the answer can change. Just open and check the stream.


Real World Example: A CSV Expenses Report

Write a data file, read it back defensively, summarise it, and produce a report — with every failure mode handled.

#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <vector>
#include <map>
#include <iomanip>
#include <optional>

struct Expense {
    std::string date;
    std::string category;
    double amount;
};

// Parse ONE line. Failure is local, so a bad row cannot derail the file.
std::optional<Expense> parseRow(const std::string& line) {
    if (line.empty() || line.front() == '#') { return std::nullopt; }  // comment

    std::istringstream fields(line);
    Expense e;
    std::string amountText;

    if (!std::getline(fields, e.date, ',')) { return std::nullopt; }
    if (!std::getline(fields, e.category, ',')) { return std::nullopt; }
    if (!std::getline(fields, amountText)) { return std::nullopt; }

    std::istringstream number(amountText);
    if (!(number >> e.amount)) { return std::nullopt; }     // not a number
    if (e.amount < 0.0) { return std::nullopt; }
    return e;
}

bool writeSample(const std::string& path) {
    std::ofstream out(path);                    // truncates -- intended here
    if (!out) { return false; }
    out << "# date,category,amount\n"
        << "2026-08-01,travel,42.30\n"
        << "2026-08-02,food,11.95\n"
        << "2026-08-02,travel,7.00\n"
        << "broken row with no commas\n"
        << "2026-08-03,food,not-a-number\n"
        << "2026-08-04,software,120.00\n";
    return static_cast<bool>(out);              // did every write succeed?
}

struct LoadReport {
    std::vector<Expense> rows;
    int skipped{0};
};

LoadReport load(const std::string& path) {
    LoadReport result;
    std::ifstream in(path);
    if (!in) { return result; }                 // empty rows, caller checks

    std::string line;
    while (std::getline(in, line)) {
        if (const auto row = parseRow(line)) {
            result.rows.push_back(*row);
        } else if (!line.empty() && line.front() != '#') {
            ++result.skipped;
        }
    }
    return result;
}

std::map<std::string, double> byCategory(const std::vector<Expense>& rows) {
    std::map<std::string, double> totals;
    for (const Expense& e : rows) { totals[e.category] += e.amount; }
    return totals;
}

bool writeReport(const std::string& path,
                 const std::map<std::string, double>& totals) {
    std::ofstream out(path);
    if (!out) { return false; }
    out << std::fixed << std::setprecision(2);
    out << "EXPENSES BY CATEGORY\n";
    double grand = 0.0;
    for (const auto& [category, total] : totals) {
        out << std::setw(12) << std::left << category
            << std::setw(10) << std::right << total << "\n";
        grand += total;
    }
    out << std::setw(12) << std::left << "TOTAL"
        << std::setw(10) << std::right << grand << "\n";
    return static_cast<bool>(out);
}

int main() {
    const std::string dataPath = "expenses.csv";
    const std::string reportPath = "expenses-report.txt";

    if (!writeSample(dataPath)) {
        std::cerr << "could not write " << dataPath << "\n";
        return 1;
    }

    const LoadReport loaded = load(dataPath);
    if (loaded.rows.empty()) {
        std::cerr << "no usable rows in " << dataPath << "\n";
        return 1;
    }
    std::cout << "loaded " << loaded.rows.size() << " row(s), skipped "
              << loaded.skipped << "\n";

    const std::map<std::string, double> totals = byCategory(loaded.rows);
    if (!writeReport(reportPath, totals)) {
        std::cerr << "could not write " << reportPath << "\n";
        return 1;
    }

    // Read the report back and echo it, proving it was flushed and closed.
    std::ifstream report(reportPath);
    std::string line;
    while (std::getline(report, line)) { std::cout << line << "\n"; }

    // Append a run marker rather than replacing the file.
    std::ofstream audit("expenses-audit.log", std::ios::app);
    audit << "run complete, " << loaded.rows.size() << " rows\n";
    return 0;
}

The structure exists to keep one bad row from costing the whole file. parseRow returns std::optional<Expense> and parses from an std::istringstream built on a single line, so the "broken row with no commas" and the not-a-number amount each fail in isolation — had the code read fields directly from the ifstream with >>, the first bad token would have set failbit and every remaining row would have been lost silently. The read loop is while (std::getline(in, line)) rather than while (!in.eof()), which is what stops the last line being processed twice. Both write functions check the stream immediately after opening and return static_cast<bool>(out) at the end, because a disk filling up mid-write sets badbit without any exception being thrown. writeSample uses truncating mode deliberately, since regenerating sample data should replace it, while the audit log opens with std::ios::app — the same call without that flag would erase every previous run's history, which is the most common file bug in production code. None of the streams call close(): each is destroyed at the end of its function, and destruction flushes, which is precisely why main can reopen and read back the report it just wrote. Comment lines beginning with # return std::nullopt too, so the skip counter distinguishes them from genuine parse failures and the reported figure means something.


Common Mistakes

  1. Not checking whether the file opened. Every subsequent read returns nothing and every write goes nowhere, silently.
  2. while (!in.eof()). The last line is processed twice. Put the read in the loop condition.
  3. Opening a log with std::ofstream out(path) instead of std::ios::app, and truncating it.
  4. Mixing >> and getline without an ignore, so the next getline returns an empty string.
  5. Reading fields straight from the file stream so that one malformed value poisons every later read. Parse line by line.
  6. Forgetting in.clear() before re-reading after end of file. All reads are no-ops until the flags are reset.
  7. Omitting std::ios::binary for non-text data, so newline bytes get translated and the file is corrupted.
  8. Writing a struct containing a std::string with write(). You are writing a pointer, not the text.
  9. std::endl in a tight loop. It flushes every iteration; use "\n".
  10. Checking exists() and then opening. Just open and test the stream.
  11. Calling close() everywhere out of habit. The destructor does it, including when an exception unwinds.

Best Practices

  • Test the stream immediately after opening, and again after the writes that matter.
  • Let scope close the file. Wrap a short-lived stream in braces if you need it shut before the function ends.
  • Read with while (std::getline(in, line)), then parse each line from an std::istringstream.
  • Return std::optional from a row parser and count the rows you skipped.
  • Open logs with std::ios::app.
  • Use std::ios::binary plus read/write for binary data, and only for trivially copyable types.
  • Prefer "\n" to std::endl unless you specifically need a flush.
  • Use std::filesystem for paths, sizes and directories rather than string manipulation.
  • Write to a temporary file and rename it when replacing important data, so a crash cannot leave a half-written file.

Practice Exercises

  1. Round trip: Write ten names and ages to a text file, read them back into a std::vector of structs, and print them. Then delete the file by hand, run the program's reading half again, and confirm your error message appears rather than a crash or silence.
  2. Prove the eof bug: Read a three-line file with while (!in.eof()) and print each line with a counter. Record how many lines print and why. Fix the loop and record the difference.
  3. Survive bad rows: Take the CSV loader above, add two more malformed rows of different kinds, and confirm the skipped count is right and every good row still loads. Then rewrite load to read fields directly with >> and record how many rows survive.
  4. Append versus truncate: Write a program that appends one timestamped line to a log on each run. Run it three times and confirm three lines. Remove std::ios::app, run it twice more, and record what happened to the history.