› Module 9: File Handling (I/O Streams) › 9.1 fstream Basics
M O D U L E

Module 9: File Handling (I/O Streams)

Reading and writing data outside the program — fstream basics, stream operators, and text vs binary modes.

9.1 fstream Basics

C++ treats files as streams of data, the same conceptual model already used for console input and output.

The <fstream> header provides three essential classes:

  • ifstream: Input file stream (for reading files from disk).
  • ofstream: Output file stream (for writing files to disk).
  • fstream: Bidirectional file stream (supporting both reading and writing).

Each behaves like cin / cout but connected directly to a file on storage instead of the terminal console.

Program (C++) write read ifstream/ofstream / fstream File on Disk (data.txt)
Figure 9.1 — Your program talks to files through stream objects

9.2 Reading & Writing Files

Writing to a file uses the same << insertion operator as cout, and reading uses the same >> extraction operator as cin — just pointed at an active file stream.

Always check that the file opened successfully before using it with if (!in.is_open()), and close it (or let its destructor close it upon scope exit) once you're done.

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

// Writing to file:
ofstream out("data.txt");
out << "Hello File";
out.close();

// Reading line-by-line:
ifstream in("data.txt");
string line;
while (getline(in, line)) {
    cout << line;
}
in.close();

9.3 Text vs Binary Files

C++ distinguishes between text and binary file processing:

  • Text mode (default): Stores data as human-readable ASCII/Unicode characters — exactly what you'd see opening the file in a text editor — with automatic newline translation (\r\n on Windows ↔ \n in memory).
  • Binary mode (ios::binary): Stores the raw bytes of data exactly as they exist in memory, which is significantly faster and more compact for structured data like numbers, images, or structs, but is not human-readable.
ofstream out("data.bin", ios::binary);
int num = 42;
out.write(reinterpret_cast<char*>(&num), sizeof(num));
out.close();
MODULE COMPREHENSIVE QUIZ

Module 9 Final Quiz

Test your understanding across all 3 topics of this module with interview-grade questions, tricky edge cases, and code output predictions.

Take Module 9 Final Quiz →
Yukti Mascot