Bytebook Compiler

Beyond the Basics

File I/O with fstream

Read and write files the C++ way with ifstream, ofstream and fstream: modes, line-by-line reading, parsing records with stringstream, and binary files.

3 min read3 runnable examples4-question quiz

C++ file handling uses streams, exactly like cin and cout. Include <fstream>:

Class Purpose
ofstream write to a file (output)
ifstream read from a file (input)
fstream both

Writing and reading text

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

int main() {
    ofstream out("notes.txt");                    // creates or truncates the file
    if (!out) { cerr << "cannot open file" << endl; return 1; }
    out << "Templates make code generic." << endl;
    out << "Exceptions separate error handling." << endl;
    out << "RAII frees resources automatically." << endl;
    out.close();

    ifstream in("notes.txt");
    string line;
    int n = 0;
    while (getline(in, line))                      // read until end of file
        cout << ++n << ": " << line << endl;
    return 0;                                     // in closes automatically (RAII)
}
Output
1: Templates make code generic.
2: Exceptions separate error handling.
3: RAII frees resources automatically.

File modes

Flag Meaning
ios::in open for reading
ios::out open for writing (truncates by default)
ios::app append: every write goes to the end
ios::ate start at the end, but allow moving around
ios::trunc erase existing contents
ios::binary binary mode (no newline translation)

Combine flags with |: fstream f("data.txt", ios::in | ios::out);

Reading structured records

Write records as text, then read them back with >> or parse each line with a stringstream:

C++
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <iomanip>
using namespace std;

int main() {
    ofstream out("students.csv");
    out << "roll,name,marks\n101,Asha,88\n102,Ravi,93\n103,Meera,79\n";
    out.close();

    ifstream in("students.csv");
    string line;
    getline(in, line);                                  // skip the header
    double total = 0;
    int count = 0;
    cout << left << setw(6) << "Roll" << setw(8) << "Name" << "Marks" << endl;
    while (getline(in, line)) {
        stringstream ss(line);
        string roll, name, marksText;
        getline(ss, roll, ',');                         // split on commas
        getline(ss, name, ',');
        getline(ss, marksText, ',');
        int marks = stoi(marksText);
        cout << setw(6) << roll << setw(8) << name << marks << endl;
        total += marks;
        count++;
    }
    cout << "Average: " << fixed << setprecision(2) << total / count << endl;

    ofstream log("students.csv", ios::app);              // append a new record
    log << "104,Kiran,85\n";
    return 0;
}
Output
Roll  Name    Marks
101   Asha    88
102   Ravi    93
103   Meera   79
Average: 86.67

Binary files

Binary I/O writes raw bytes — compact and fast, but not human-readable:

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

struct Reading { int sensor; double value; };

int main() {
    Reading data[3] = {{1, 21.5}, {2, 22.25}, {3, 19.75}};
    ofstream out("readings.bin", ios::binary);
    out.write(reinterpret_cast<const char *>(data), sizeof(data));
    out.close();

    ifstream in("readings.bin", ios::binary);
    in.seekg(sizeof(Reading) * 2);                   // jump to the third record
    Reading r;
    in.read(reinterpret_cast<char *>(&r), sizeof(r));
    cout << "sensor " << r.sensor << " read " << r.value << endl;
    cout << "file size: " << sizeof(data) << " bytes" << endl;
    return 0;
}
Output
sensor 3 read 19.75
file size: 48 bytes

seekg / tellg move and report the get (read) position; seekp / tellp do the same for the put (write) position.

Test yourself

4 questions · pick an answer to check it instantly

  1. 1

    Which class do you use to read from a file?

  2. 2

    How do you open log.txt so new writes are added at the end?

  3. 3

    What does while (getline(in, line)) stop on?

  4. 4

    Why is it often unnecessary to call close() explicitly on file streams?