C++ · Module 16 · Lesson 11 min read

ifstream & ofstream Basics

File stream classes (<fstream>)

ClassPurpose
std::ofstreamwrite to a file
std::ifstreamread from a file
std::fstreamread and write

They work exactly like std::cout/std::cin: out << x;, in >> x;, std::getline(in, line);

Writing

csharp
std::ofstream out("expenses.txt");      // creates or OVERWRITES
if (!out) { /* could not open */ }
out << "Food " << 450 << '\n';

Reading

c
std::ifstream in("expenses.txt");
if (!in) { std::cerr << "cannot open\n"; return; }
std::string category; double amount;
while (in >> category >> amount) { ... }   // stops at end of file or bad data

Open modes (std::ios::)

ModeMeaning
inread
outwrite (truncates by default)
appappend: always write at the end
truncerase existing contents
binaryno newline translation (lesson 16.3)
atestart at the end
Combine with `: std::ofstream log("app.log", std::ios::app);`

Closing — RAII again ✅

The destructor closes the file automatically when the stream goes out of scope. Call .close() only if you need to reopen or check for errors before the scope ends.

Always check

  • if (!file) / if (!file.is_open()) after opening
  • The read operation itself in the loop condition (while (in >> x)) — never while (!in.eof()) ❌ (processes the last item twice or loops on bad data)

Stream state

good(), eof() (end reached), fail() (bad format or failed op), bad() (serious I/O error), clear() to reset.

Paths

Relative paths are relative to the working directory the program runs from, not the source file's folder. Use std::filesystem (lesson 16.4) for robust paths.

Example

C++
#include <fstream>
#include <iostream>
#include <string>

int main() {
    {
        std::ofstream out("expenses.txt");               // create / overwrite
        if (!out) { std::cerr << "cannot create file\n"; return 1; }
        out << "Food 450\n" << "Rent 15000\n" << "Travel 300\n";
    }                                                     // closed automatically here

    {
        std::ofstream log("expenses.txt", std::ios::app); // append mode keeps existing lines
        log << "Food 1200\n";
    }

    std::ifstream in("expenses.txt");
    if (!in) { std::cerr << "cannot open file\n"; return 1; }
    std::string category;
    double amount, total = 0;
    int count = 0;
    while (in >> category >> amount) {                   // check the read itself
        std::cout << "  " << category << ": " << amount << '\n';
        total += amount;
        ++count;
    }
    std::cout << count << " expenses, total " << total << '\n';
    std::cout << std::boolalpha << "eof reached? " << in.eof() << '\n';

    std::ifstream missing("no_such_file.txt");
    if (!missing) std::cout << "no_such_file.txt could not be opened\n";

    std::ifstream again("expenses.txt");
    std::string line;
    int line_no = 0;
    while (std::getline(again, line)) ++line_no;           // count lines
    std::cout << "file has " << line_no << " lines\n";
    return 0;
}

/* Output:
  Food: 450
  Rent: 15000
  Travel: 300
  Food: 1200
4 expenses, total 16950
eof reached? true
no_such_file.txt could not be opened
file has 4 lines
*/