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.
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\non Windows ↔\nin 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();