LearnFrenzy
Sign in Take a free test

C++ Programming · Topic 26 of 27

File Handling (fstream)

  • 4 exercises
  • 60 questions
  • ~60 min
  • Answers explained

Introduction & Syntax

File Handling (fstream) · Study material

File handling in C++ lets a program keep data after it ends: saving settings, writing logs, reading CSV exports, storing records, generating reports. The <fstream> header provides three stream classes – std::ofstream for writing, std::ifstream for reading and std::fstream for both – that work exactly like std::cout and std::cin, so <<, >> and getline all carry over. C++17's std::filesystem adds paths, directories, sizes, copying and deleting. This page covers opening and checking files, open modes, the different ways of reading, stream error states, binary files and random access, string streams and the filesystem library, with programs you can run. Then practise with 60 questions – 20 MCQs, 20 predict-the-output puzzles, 10 find-the-error programs and 10 complete programs – all verified on a real C++ compiler.

On this page

  • ofstream, ifstream and fstream; opening, checking and closing files
  • Open modes: in, out, app, trunc, ate, binary
  • Reading line by line, word by word, character by character and all at once
  • Stream state flags: good, eof, fail, bad, and clear()
  • Binary files, seekg/seekp/tellg and random access
  • stringstream, stream exceptions and std::filesystem

Writing and reading a text file

Create a stream with a file name (or call open()), check that it opened with if (!stream) or is_open(), then use it like cout/cin. The file is closed automatically when the stream object is destroyed – call close() only when you need to close it earlier.

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

int main() {
    const auto path = std::filesystem::temp_directory_path() / "lf_students.txt";

    {   // ofstream: open for writing (creates or truncates the file)
        std::ofstream out(path);
        if (!out) { std::cerr << "cannot open for writing\n"; return 1; }
        out << "Asha 91\n" << "Ravi 78\n" << "Meena 85\n";
    }   // closed automatically here (RAII) – data is flushed to disk

    std::ifstream in(path);                // ifstream: open for reading
    if (!in.is_open()) { std::cerr << "cannot open for reading\n"; return 1; }
    std::string name;
    int marks, total = 0, count = 0;
    while (in >> name >> marks) {          // the loop stops when extraction fails (end of file)
        std::cout << name << " scored " << marks << '\n';
        total += marks;
        ++count;
    }
    std::cout << "average " << total / count << '\n';
    in.close();
    std::filesystem::remove(path);
    return 0;
}

Output

Asha scored 91
Ravi scored 78
Meena scored 85
average 84

Open modes

ModeMeaning
std::ios::inopen for reading (default for ifstream)
std::ios::outopen for writing (default for ofstream; truncates unless app or in is also given)
std::ios::appevery write goes to the end of the file
std::ios::truncdiscard existing contents on opening
std::ios::atestart at the end, but writes may later move elsewhere
std::ios::binaryno newline translation (important on Windows); use for raw bytes

Combine modes with |, for example std::ios::in | std::ios::out to update a file in place.

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

void show(const std::filesystem::path& p) {
    std::ifstream in(p);
    std::string line;
    while (std::getline(in, line)) std::cout << "  " << line << '\n';
}

int main() {
    const auto log = std::filesystem::temp_directory_path() / "lf_app.log";

    std::ofstream(log) << "started\n";                          // default mode: out | trunc
    std::ofstream(log, std::ios::app) << "user login\n";         // app: always write at the end
    std::ofstream(log, std::ios::app) << "user logout\n";
    std::cout << "after appends:\n";
    show(log);

    std::ofstream(log, std::ios::trunc) << "fresh start\n";     // trunc: discard old contents
    std::cout << "after truncate:\n";
    show(log);
    std::filesystem::remove(log);
    return 0;
}

Output

after appends:
  started
  user login
  user logout
after truncate:
  fresh start

Four ways to read

std::getline reads whole lines (keeping spaces); >> reads whitespace-separated words or numbers; get(c) reads every character including spaces and newlines; and rdbuf() copies the whole file at once. Always loop on the read operation itself – while (std::getline(in, line)) – never on !in.eof().

#include <filesystem>
#include <fstream>
#include <iostream>
#include <sstream>
#include <string>

int main() {
    const auto p = std::filesystem::temp_directory_path() / "lf_poem.txt";
    std::ofstream(p) << "Learn C++ daily\n\nPractice makes perfect\n";

    std::ifstream in(p);
    int lines = 0;
    for (std::string line; std::getline(in, line); ) ++lines;      // 1. line by line (keeps spaces)

    in.clear();                     // reset the eof/fail flags…
    in.seekg(0);                    // …and go back to the beginning
    int words = 0;
    for (std::string w; in >> w; ) ++words;                        // 2. word by word (skips whitespace)

    in.clear(); in.seekg(0);
    int chars = 0, vowels = 0;
    for (char c; in.get(c); ) {                                    // 3. character by character (includes '\n')
        ++chars;
        if (std::string("aeiouAEIOU").find(c) != std::string::npos) ++vowels;
    }

    in.clear(); in.seekg(0);
    std::stringstream whole;
    whole << in.rdbuf();                                           // 4. the whole file at once
    std::cout << lines << " lines, " << words << " words, " << chars << " chars, " << vowels << " vowels, "
              << whole.str().size() << " bytes\n";
    in.close();
    std::filesystem::remove(p);
    return 0;
}

Output

3 lines, 6 words, 40 chars, 11 vowels, 40 bytes

Stream state flags

FunctionTrue when
good()no error flags are set
eof()a read tried to go past the end of the file
fail()an operation failed (file not opened, wrong data for >>, or end of file)
bad()a serious, unrecoverable I/O error
operator bool / !the stream is usable (= !fail())

Once a flag is set, every further operation does nothing until you call clear().

#include <filesystem>
#include <fstream>
#include <iostream>

int main() {
    std::ifstream missing(std::filesystem::temp_directory_path() / "lf_does_not_exist.txt");
    std::cout << "open " << missing.is_open() << " fail " << missing.fail() << '\n';

    const auto p = std::filesystem::temp_directory_path() / "lf_numbers.txt";
    std::ofstream(p) << "10 20 abc 30";
    std::ifstream in(p);
    int x, sum = 0;
    while (in >> x) sum += x;              // stops at "abc": failbit set, but NOT end of file
    std::cout << "sum " << sum << " good " << in.good() << " eof " << in.eof() << " fail " << in.fail() << '\n';

    in.clear();                            // clear the error flags…
    std::string junk;
    in >> junk;                            // …skip the bad word…
    while (in >> x) sum += x;              // …and continue
    std::cout << "skipped '" << junk << "', sum " << sum << " eof " << in.eof() << '\n';
    in.close();
    std::filesystem::remove(p);
    return 0;
}

Output

open 0 fail 1
sum 30 good 0 eof 0 fail 1
skipped 'abc', sum 60 eof 1

Binary files

Binary mode stores raw bytes with write() and read(): compact and fast, with fixed-size records you can jump to directly. Only do this with trivially copyable types (no std::string, no pointers), and remember that the format depends on the machine's sizes, padding and byte order.

#include <cstdint>
#include <filesystem>
#include <fstream>
#include <iostream>
#include <type_traits>
#include <vector>

struct Record {                 // trivially copyable: safe to write as raw bytes
    std::int32_t id;
    float price;
    char code[8];
};
static_assert(std::is_trivially_copyable_v<Record>);

int main() {
    const auto p = std::filesystem::temp_directory_path() / "lf_records.bin";
    std::vector<Record> out{{1, 9.5f, "PEN"}, {2, 120.0f, "BOOK"}, {3, 45.25f, "INK"}};
    {
        std::ofstream f(p, std::ios::binary);
        f.write(reinterpret_cast<const char*>(out.data()), static_cast<std::streamsize>(out.size() * sizeof(Record)));
    }
    std::cout << "file size " << std::filesystem::file_size(p) << " = " << out.size() << " x " << sizeof(Record) << '\n';

    std::ifstream f(p, std::ios::binary);
    f.seekg(2 * sizeof(Record));                     // random access: jump straight to record #3
    Record r{};
    f.read(reinterpret_cast<char*>(&r), sizeof r);
    std::cout << r.id << ' ' << r.code << ' ' << r.price << ' ' << f.gcount() << " bytes read\n";
    f.close();
    std::filesystem::remove(p);
    return 0;
}

Output

file size 48 = 3 x 16
3 INK 45.25 16 bytes read

Random access: seekg, seekp, tellg, tellp

Input streams have a "get" position and output streams a "put" position. seekg(pos)/seekp(pos) move them (optionally relative to std::ios::beg, cur or end); tellg()/tellp() report them.

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

int main() {
    const auto p = std::filesystem::temp_directory_path() / "lf_seats.txt";
    std::ofstream(p) << "..........";                 // 10 free seats

    // fstream with in | out: read AND write the same file without truncating it
    std::fstream f(p, std::ios::in | std::ios::out);
    for (int seat : {2, 5, 9}) {
        f.seekp(seat);                                // move the write position
        f.put('X');
    }
    f.seekg(0, std::ios::end);
    std::cout << "length " << f.tellg() << '\n';      // tellg at the end = file size
    f.seekg(0);
    std::string all;
    std::getline(f, all);
    std::cout << all << " free=" << std::count(all.begin(), all.end(), '.') << '\n';
    f.close();
    std::filesystem::remove(p);
    return 0;
}

Output

length 10
..X..X...X free=7

std::filesystem (C++17)

std::filesystem::path builds paths portably with /; functions like exists, file_size, create_directories, copy_file, rename, remove and remove_all manage files, and directory_iterator / recursive_directory_iterator list them. Directory iteration order is unspecified – sort if order matters.

#include <algorithm>
#include <filesystem>
#include <fstream>
#include <iostream>
#include <string>
#include <vector>

namespace fs = std::filesystem;

int main() {
    const fs::path dir = fs::temp_directory_path() / "lf_reports_demo";
    fs::remove_all(dir);
    fs::create_directories(dir / "2025");
    std::ofstream(dir / "2025" / "jan.csv") << "a,b\n1,2\n";
    std::ofstream(dir / "2025" / "feb.csv") << "a,b\n3,4\n5,6\n";
    std::ofstream(dir / "notes.txt") << "hello";

    fs::path p = dir / "2025" / "feb.csv";
    std::cout << p.filename().string() << ' ' << p.stem().string() << ' ' << p.extension().string() << ' '
              << fs::exists(p) << ' ' << fs::file_size(p) << '\n';

    std::vector<std::string> csv;                                  // iteration order is unspecified…
    for (const auto& e : fs::recursive_directory_iterator(dir))
        if (e.is_regular_file() && e.path().extension() == ".csv") csv.push_back(e.path().filename().string());
    std::sort(csv.begin(), csv.end());                             // …so sort before printing
    for (const auto& name : csv) std::cout << name << ' ';

    fs::rename(dir / "notes.txt", dir / "readme.txt");
    std::cout << "| " << fs::exists(dir / "notes.txt") << fs::exists(dir / "readme.txt") << ' ';
    std::cout << fs::remove_all(dir) << " items removed\n";
    return 0;
}

Output

feb.csv feb .csv 1 12
feb.csv jan.csv | 01 5 items removed

Common mistakes

  • Not checking that the file opened – every later read silently fails.
  • while (!in.eof()) – processes the last item twice or loops forever on bad data; loop on the read instead.
  • Forgetting clear() before seekg(0) after reaching the end – the stream stays failed.
  • Mixing >> and getline without skipping the leftover newline (use std::ws).
  • Overwriting data by accident – ofstream truncates by default; use std::ios::app to add.
  • Writing std::string or pointers with write() – you store addresses, not text.
  • Hard-coded paths with backslashes – use std::filesystem::path and /.

Key points to remember

  • ofstream writes, ifstream reads, fstream does both.
  • Check if (!file) after opening; files close automatically (RAII).
  • ofstream truncates by default; std::ios::app appends.
  • Loop on the read: while (std::getline(in, line)), while (in >> x).
  • clear() resets error flags; seekg/seekp move positions.
  • Binary I/O with read/write only for trivially copyable data.
  • Use std::filesystem for paths, sizes, directories and deleting files.

Frequently asked questions

Do I need to call close()?

No – the destructor closes the file. Call close() when you want to close it early, for example before reopening or deleting it.

What is the difference between text and binary mode?

Text mode may translate line endings (\n ↔ \r\n on Windows); binary mode reads and writes bytes exactly as they are.

How do I read a whole file into a string?

std::ostringstream ss; ss << in.rdbuf(); std::string all = ss.str(); – or read file_size bytes into a string with in.read().

Where can I learn more?

Read C++ Input/Output, then practise with the exercises below.

Ready to test your Programming?

Timed online tests with instant scores and explanations.

About this section

About C++ Programming

C++ adds object-oriented programming, templates and the powerful Standard Template Library (STL) to C. It powers game engines, browsers, trading systems and most competitive programming. This section takes you from basic syntax to classes, inheritance, polymorphism, modern C++ (C++11 to C++23) and the STL – every concept with runnable examples and practice questions checked on a real compiler.

Why it matters

  • OOP concepts – classes, inheritance, polymorphism, encapsulation – are asked in almost every interview
  • C++ with the STL is the most popular language for competitive programming and DSA rounds
  • Questions on constructors, virtual functions, references and smart pointers decide technical rounds
  • Modern C++ skills are in demand at product companies, fintech and game studios

Who it is for

  • School students (Class 11–12 computer science with C++) preparing for board exams and practicals
  • College students (B.Tech, BCA, MCA) learning OOP and data structures for semester exams and labs
  • Freshers preparing for placements, coding tests and C++ technical interviews
  • Competitive programmers who want to master the STL

What every topic gives you

  • Study material in five tabs: concepts with runnable examples, coding techniques, programs, interview questions and a cheat sheet
  • MCQs that check your understanding of every concept
  • "Predict the output" puzzles – the trickiest part of written tests
  • "Find the error" programs that train you to spot bugs quickly
  • Complete programs with solutions and real output, verified on a compiler

Asked in

  • Campus placements
  • Product company interviews
  • Coding rounds & DSA
  • Competitive programming
  • GATE CS
  • University exams

How to use this section

  1. Read the study material of a topic and run the examples yourself.
  2. Practise the four exercises – MCQs, output, errors, programs – and read every explanation.
  3. Test yourself with the timed online test, then revise the topics you got wrong.

Search LearnFrenzy

Esc

Quick links