So far, every program we wrote forgot everything the moment it ended. Marks typed in, results computed, and all of it gone when main returned. Real programs need to persist data: save a game, read a configuration, process a CSV exported from Excel, write a log. All of that is done with files.
The good news: you already know most of what you need. In Input & Output we learned that std::cin and std::cout are streams. C++ file handling uses exactly the same stream model: a file stream is just a stream connected to a file instead of the keyboard or screen. Every <<, >>, getline and manipulator you know works on files unchanged. In this chapter we learn to open files correctly, read them safely, handle errors, work with binary data and random access, and manage files and folders with C++17's <filesystem>.
The File Stream Classes
The header
<fstream>provides three classes:std::ifstream(input file stream, for reading),std::ofstream(output file stream, for writing) andstd::fstream(for both reading and writing).
ios_base
│
ios
┌──────┴──────┐
istream ostream (cin is an istream,
│ └───┬───┘ │ cout is an ostream)
ifstream iostream ofstream
┌───┴──────┐
fstream stringstreamBecause ifstream inherits from istream, any function written to take std::istream& works with std::cin, a file, or a std::stringstream. This is inheritance and polymorphism from earlier chapters doing real work for you.
File streams follow RAII (see Smart Pointers): the constructor opens the file and the destructor closes it automatically, even if an exception is thrown. They are also move-only (see Move Semantics & Rvalue References): you can return an std::ifstream from a function, but you cannot copy one, because two objects closing the same file would make no sense.
Writing and Reading a Text File
The basic steps are always the same: open, check, read or write, and (automatically) close.
#include <fstream>
#include <iostream>
#include <string>
int main() {
// ---- Writing ----
std::ofstream out("students.txt"); // creates the file (or empties it)
if (!out) { // always check that opening worked
std::cerr << "Cannot create students.txt\n";
return 1;
}
out << "Asha 78\n";
out << "Ravi 91\n";
out << "Meena 65\n";
out.close(); // optional: the destructor also closes
// ---- Reading line by line ----
std::ifstream in("students.txt");
if (!in) {
std::cerr << "Cannot open students.txt\n";
return 1;
}
std::string line;
int lineNo = 0;
while (std::getline(in, line)) { // stops when no more lines can be read
std::cout << ++lineNo << ": " << line << '\n';
}
// ---- Reading formatted values (word by word) ----
std::ifstream in2("students.txt");
std::string name;
int marks, total = 0, count = 0;
while (in2 >> name >> marks) { // stops when extraction fails
total += marks;
++count;
}
std::cout << "Average of " << count << " students = "
<< static_cast<double>(total) / count << '\n';
}Output:
1: Asha 78
2: Ravi 91
3: Meena 65
Average of 3 students = 78The file students.txt created next to the program contains:
Asha 78
Ravi 91
Meena 65Key points:
Opening: pass the path to the constructor, or default-construct and call
open(path)later. A relative path like"students.txt"is resolved against the program's current working directory, which is not necessarily the folder containing the source code. That is the most common reason for "my file is not found" in IDEs.Checking: a stream converts to
bool;if (!in)is true when opening failed (missing file, no permission, wrong folder). You can also usein.is_open(). Never skip this check: reading from a stream that failed to open silently reads nothing.Closing: the destructor closes the file. Calling
close()explicitly is useful when you want to reopen or read the same file in the same scope, as we did before reading.Two styles of reading:
std::getline(in, line)reads a whole line (spaces included, newline removed);in >> name >> marksreads whitespace-separated values and converts them to the right type.
The Right Way to Loop Over a File
Every stream operation returns the stream itself, and a stream tests as true only if the last operation succeeded. So the read operation itself should be the loop condition: while (std::getline(in, line)) or while (in >> x). Many students instead write while (!in.eof()), which looks logical but is wrong:
#include <fstream>
#include <iostream>
int main() {
std::ofstream("nums.txt") << "10 20 30\n"; // a temporary stream: written and closed at once
// WRONG: testing eof() before reading
std::ifstream in("nums.txt");
int x = 0, count = 0, sum = 0;
while (!in.eof()) {
in >> x; // the 4th attempt fails, but we still use x
++count;
sum += x;
}
std::cout << "eof loop: count = " << count << ", sum = " << sum << '\n';
// RIGHT: use the read operation itself as the condition
std::ifstream in2("nums.txt");
count = sum = 0;
while (in2 >> x) {
++count;
sum += x;
}
std::cout << "correct loop: count = " << count << ", sum = " << sum << '\n';
}Output:
eof loop: count = 4, sum = 90
correct loop: count = 3, sum = 60Why did the eof loop count four numbers and add 30 twice?
After reading 30, the stream stops right before the final
'\n'. It has not tried to read past the end yet, soeof()is still false.The loop runs a fourth time.
in >> xskips the newline, hits the end of file, and fails. Since no characters could be read at all,xkeeps its old value 30.The loop body uses
xanyway: count becomes 4, and 30 is added again.
eof()becomes true only after a read operation has tried to go past the end. It tells you why the last read failed, not whether the next read will succeed. Always test the result of the read itself.
Open Modes
The second constructor argument (or open argument) is a combination of flags from std::ios (also written std::ios_base), joined with |:
| Flag | Meaning |
|---|---|
std::ios::in | Open for reading (default for ifstream) |
std::ios::out | Open for writing (default for ofstream). On its own it truncates an existing file |
std::ios::app | Append: every write goes to the end of the file |
std::ios::ate | "At end": start positioned at the end, but you may seek elsewhere afterwards |
std::ios::trunc | Discard existing contents on opening |
std::ios::binary | No text translation (e.g. Windows \r\n ↔ \n) |
std::ios::noreplace (C++23) | Exclusive creation: opening fails if the file already exists |
The common combinations, and what happens when the file exists or does not:
| Mode | File exists | File missing | Like C's fopen |
|---|---|---|---|
in | Read from start | Fails | "r" |
out or out | trunc | Emptied, then written | Created | "w" |
app or out | app | Writes appended | Created | "a" |
in | out | Read/write, contents kept | Fails | "r+" |
in | out | trunc | Emptied, read/write | Created | "w+" |
out | noreplace (C++23) | Fails | Created | "wx" |
#include <fstream>
#include <iostream>
#include <string>
void show(const char* path) {
std::ifstream in(path);
std::string line;
while (std::getline(in, line)) std::cout << " " << line << '\n';
}
int main() {
{
std::ofstream log("log.txt"); // default: out | trunc
log << "server started\n";
}
{
std::ofstream log("log.txt", std::ios::app); // append: every write goes to the end
log << "user logged in\n";
log << "user logged out\n";
}
std::cout << "After appending:\n";
show("log.txt");
{
std::ofstream log("log.txt"); // opening again without app: truncated!
log << "fresh start\n";
}
std::cout << "After reopening with default mode:\n";
show("log.txt");
// C++23: noreplace fails if the file already exists (exclusive creation)
std::ofstream guard("log.txt", std::ios::out | std::ios::noreplace);
std::cout << "noreplace on existing file opened? " << std::boolalpha
<< guard.is_open() << '\n';
}Output:
After appending:
server started
user logged in
user logged out
After reopening with default mode:
fresh start
noreplace on existing file opened? falseNotice how dangerous the default ofstream mode is: simply opening an existing file for writing erased "server started" and the two log lines. Use std::ios::app for logs, and the C++23 noreplace flag when you must never overwrite an existing file. Also note the in | out row: std::fstream's default mode does not create a missing file.
Worked Example: Processing a CSV File
CSV (comma-separated values) files are everywhere: exported marks sheets, bank statements, datasets. The standard pattern is: read a line with getline, wrap the line in a std::stringstream, and split it with getline(ss, field, ','), using the comma as the delimiter.
#include <fstream>
#include <iomanip>
#include <iostream>
#include <sstream>
#include <stdexcept>
#include <string>
#include <vector>
struct Result {
std::string name;
int maths, physics, chemistry;
double average() const { return (maths + physics + chemistry) / 3.0; }
};
int main() {
// Prepare an input file (normally it would already exist)
std::ofstream("results.csv") << "name,maths,physics,chemistry\n"
"Asha,78,85,90\n"
"Ravi,91,72,88\n"
"Meena,abc,70,60\n"
"John,55,61,49\n";
std::ifstream in("results.csv");
if (!in) { std::cerr << "cannot open results.csv\n"; return 1; }
std::vector<Result> results;
std::string line;
std::getline(in, line); // skip the header row
int lineNo = 1;
while (std::getline(in, line)) {
++lineNo;
std::stringstream ss(line); // treat the line itself as a stream
std::string name, m, p, c;
std::getline(ss, name, ','); // read up to each comma
std::getline(ss, m, ',');
std::getline(ss, p, ',');
std::getline(ss, c, ',');
try {
results.push_back({name, std::stoi(m), std::stoi(p), std::stoi(c)});
} catch (const std::invalid_argument&) {
std::cout << "line " << lineNo << " skipped: bad number\n";
}
}
std::ofstream report("report.txt");
report << std::fixed << std::setprecision(2);
for (const auto& r : results)
report << std::left << std::setw(8) << r.name << r.average() << '\n';
report.close();
std::cout << "report.txt contains:\n";
std::ifstream check("report.txt");
std::cout << check.rdbuf(); // print the whole file at once
}Output:
line 4 skipped: bad number
report.txt contains:
Asha 84.33
Ravi 83.67
John 55.00Points to learn from this example:
std::ofstream("results.csv") << ...creates a temporary stream that writes and is closed at the end of the statement. Handy for quick test files.Real input contains bad data.
std::stoi("abc")throwsstd::invalid_argument(andstd::out_of_rangefor huge numbers), so the bad row was reported and skipped instead of crashing the program. Be aware thatstoi("78abc")happily returns 78; usestd::from_chars(C++17, header<charconv>) if you need strict checking.The same manipulators from Input & Output (
std::fixed,std::setprecision,std::setw,std::left) format the report file.std::cout << check.rdbuf();prints a whole file at once by connecting the file's stream buffer directly tocout.This simple splitting does not handle quoted fields like
"Sharma, Ravi"; real CSV with quotes needs a proper parser.
Binary Files
Text files store numbers as characters: the int 1234567 becomes 7 characters, and must be parsed back. Binary files store the raw bytes of objects exactly as they are in memory: an int is always 4 bytes, and reading is a straight memory copy. This is faster, gives fixed-size records, and allows jumping directly to record number k.
We use the unformatted functions write(const char* bytes, count) and read(char* bytes, count), and the file must be opened with std::ios::binary. Since these functions work with char*, we convert the object's address with reinterpret_cast (from Type Conversion & Casting).
#include <cstring>
#include <fstream>
#include <iostream>
#include <type_traits>
struct Record {
int id;
char name[20]; // fixed-size array, NOT std::string
double cgpa;
};
static_assert(std::is_trivially_copyable_v<Record>); // safe to write as raw bytes
void printAll(const char* path) {
std::ifstream in(path, std::ios::binary);
Record r;
while (in.read(reinterpret_cast<char*>(&r), sizeof r))
std::cout << " " << r.id << ' ' << r.name << ' ' << r.cgpa << '\n';
}
int main() {
Record data[3] = {{1, "Asha", 8.7}, {2, "Ravi", 9.1}, {3, "Meena", 7.9}};
{
std::ofstream out("records.dat", std::ios::binary);
out.write(reinterpret_cast<const char*>(data), sizeof data); // all 3 at once
}
std::cout << "sizeof(Record) = " << sizeof(Record) << '\n';
std::ifstream in("records.dat", std::ios::binary | std::ios::ate); // start at the end
std::cout << "file size = " << in.tellg() << " bytes\n";
in.close();
std::cout << "All records:\n";
printAll("records.dat");
// Random access: update record #2 (index 1) in place
std::fstream io("records.dat", std::ios::in | std::ios::out | std::ios::binary);
Record r;
io.seekg(1 * sizeof(Record)); // jump straight to it
io.read(reinterpret_cast<char*>(&r), sizeof r);
r.cgpa = 9.4;
std::strcpy(r.name, "Ravi K");
io.seekp(1 * sizeof(Record)); // move the write position back
io.write(reinterpret_cast<const char*>(&r), sizeof r);
io.close();
std::cout << "After updating record 2:\n";
printAll("records.dat");
}Output (GCC 15, x86-64):
sizeof(Record) = 32
file size = 96 bytes
All records:
1 Asha 8.7
2 Ravi 9.1
3 Meena 7.9
After updating record 2:
1 Asha 8.7
2 Ravi K 9.4
3 Meena 7.9Random Access with seekg and seekp
Every file stream has a current position. Input streams have a get position, output streams a put position (for file streams the two move together, but use the matching function anyway):
| Function | Purpose |
|---|---|
tellg() / tellp() | Current read / write position (in bytes from the start) |
seekg(pos) / seekp(pos) | Jump to absolute position pos |
seekg(off, std::ios::beg / cur / end) | Jump relative to the beginning, current position, or end |
Because every record is exactly sizeof(Record) bytes, record k (0-based) starts at byte k * sizeof(Record). That is how databases implement fixed-length records: O(1) access to any record without reading the earlier ones. Opening with ate and calling tellg() gave the file size, and dividing by 32 gives the record count. Note that when you switch from reading to writing on an fstream, you must seek in between, as we did with seekp.
Binary I/O Limitations
Only trivially copyable types. A
std::stringorstd::vectormember stores a pointer to heap memory. Writing its bytes writes the pointer, which is meaningless when read back by another run. That is whyRecorduseschar name[20], and why we added astatic_assertwithstd::is_trivially_copyable_v.Padding: the compiler may insert padding bytes between members for alignment. Here 4 + 20 + 8 = 32 happens to need none, but swapping member order could change
sizeof.Portability: sizes of types, padding and byte order (endianness) can differ between compilers and machines, so such files are only reliably readable by the same program on the same platform. For data exchange use text formats (CSV, JSON) or a defined binary format that writes each field explicitly.
Text Mode vs Binary Mode
| Text mode (default) | Binary mode (std::ios::binary) | |
|---|---|---|
| Typical functions | <<, >>, getline | read, write |
| Data stored as | Human-readable characters | Raw memory bytes |
| Newline handling | '\n' may be translated (to \r\n on Windows) | Bytes written exactly as given |
| Size of the number 1234567 | 7 bytes | sizeof(int), typically 4 bytes |
| Random access to record k | Difficult (variable-length lines) | Easy with fixed-size records |
| Portable / editable | Yes, open in any editor | No |
On Linux and macOS text and binary mode behave the same, but always use std::ios::binary for binary data so your program also works on Windows, where a byte with value 10 would otherwise be written as two bytes.
Stream States and Error Handling
Every stream keeps three error flags: eofbit, failbit and badbit (the value goodbit simply means none of them is set). Knowing them lets you tell "end of file" apart from "bad data" and from a real I/O error:
| Function | True when |
|---|---|
good() | No flag is set; the stream is ready |
eof() | A read reached the end of the input (eofbit) |
fail() | The last operation failed: open failure, bad format, or nothing left to read (failbit or badbit) |
bad() | A serious, usually unrecoverable error such as a disk read error (badbit) |
clear() | Resets all flags so the stream can be used again |
#include <fstream>
#include <iostream>
#include <string>
void report(const char* label, const std::ios& s) {
std::cout << label << ": good=" << s.good() << " eof=" << s.eof()
<< " fail=" << s.fail() << " bad=" << s.bad() << '\n';
}
int main() {
std::ifstream missing("no_such_file.txt");
std::cout << "is_open = " << missing.is_open() << '\n';
report("missing file ", missing);
std::ofstream("data.txt") << "42 abc";
std::ifstream in("data.txt");
int n;
in >> n;
report("after reading 42", in);
in >> n; // "abc" is not an int
report("after 'abc' ", in);
in.clear(); // reset the flags...
std::string word;
in >> word; // ...and the stream works again
std::cout << "recovered word = " << word << '\n';
report("at end of file ", in);
// Make the stream throw instead of setting flags silently
std::ifstream strict;
strict.exceptions(std::ios::failbit | std::ios::badbit);
try {
strict.open("no_such_file.txt");
} catch (const std::ios_base::failure& e) {
std::cout << "exception caught: std::ios_base::failure\n";
}
}Output:
is_open = 0
missing file : good=0 eof=0 fail=1 bad=0
after reading 42: good=1 eof=0 fail=0 bad=0
after 'abc' : good=0 eof=0 fail=1 bad=0
recovered word = abc
at end of file : good=0 eof=1 fail=0 bad=0
exception caught: std::ios_base::failureAs in Input & Output, a failed stream stays failed: after "abc" could not be read as an int, every further read would do nothing until clear() was called. Reading "abc" as a string then succeeded, and because it ended exactly at the end of the file, eofbit was set while failbit was not: the read succeeded and also discovered the end.
By default streams never throw. Calling exceptions(std::ios::failbit | std::ios::badbit) makes them throw std::ios_base::failure instead, which suits code that treats a missing file as an exceptional situation. Be careful: with failbit in the mask, the normal "read until it fails" loop will also throw at the end of the file.
Managing Files and Folders: std::filesystem (C++17)
File streams read and write file contents. To work with the files themselves (check existence, get sizes, create folders, list a directory, rename, delete) C++17 added the <filesystem> library. Before C++17 this needed OS-specific calls or the Boost library.
#include <algorithm>
#include <filesystem>
#include <fstream>
#include <iostream>
#include <string>
#include <vector>
namespace fs = std::filesystem; // a common short alias
int main() {
fs::path dir = "exam_data";
fs::create_directories(dir / "archive"); // creates parent folders too
for (std::string name : {"maths.txt", "physics.txt", "notes.md"})
std::ofstream(dir / name) << "content of " << name << '\n';
std::cout << std::boolalpha;
std::cout << "exists(maths.txt): " << fs::exists(dir / "maths.txt") << '\n';
std::cout << "size of maths.txt: " << fs::file_size(dir / "maths.txt") << " bytes\n";
fs::path p = dir / "physics.txt";
std::cout << "filename: " << p.filename() << ", stem: " << p.stem()
<< ", extension: " << p.extension() << '\n';
fs::rename(dir / "notes.md", dir / "archive" / "notes.md"); // move a file
// List the directory (order from the OS is unspecified, so sort it)
std::vector<std::string> entries;
for (const auto& entry : fs::directory_iterator(dir))
entries.push_back(entry.path().filename().string() +
(entry.is_directory() ? "/" : ""));
std::sort(entries.begin(), entries.end());
std::cout << "contents of exam_data:";
for (const auto& e : entries) std::cout << ' ' << e;
std::cout << '\n';
auto removed = fs::remove_all(dir); // deletes everything inside, too
std::cout << "removed " << removed << " files and folders\n";
std::cout << "exists(exam_data): " << fs::exists(dir) << '\n';
}Output:
exists(maths.txt): true
size of maths.txt: 21 bytes
filename: "physics.txt", stem: "physics", extension: ".txt"
contents of exam_data: archive/ maths.txt physics.txt
removed 5 files and folders
exists(exam_data): falsestd::filesystem::pathrepresents a path; the/operator joins parts with the correct separator for the operating system. File streams accept apathdirectly.Printing a
pathwith<<puts it in quotes (that is why"physics.txt"appears quoted). Use.string()for the raw text.The order of
directory_iteratorentries is unspecified, so we sorted them. Userecursive_directory_iteratorto walk subfolders.remove_alldeleted the folder and everything inside it (5 items: the 2 folders and 3 files) and returned the count. Likerm -rf, use it carefully.Most functions throw
std::filesystem::filesystem_erroron failure; each also has an overload taking astd::error_code&that reports the error without throwing.
C++23 std::print to Files, and Copying a File
In Input & Output we met std::print. In C++23, std::print and std::println also accept any std::ostream as the first argument (these overloads are declared in <ostream>), so they work with file streams. And the rdbuf() trick copies an entire file in one statement:
#include <fstream>
#include <iostream>
#include <print> // C++23
#include <string>
int main() {
// C++23 std::print / std::println can write directly to any std::ostream
std::ofstream out("marks.txt");
std::println(out, "{:<8}{:>5}", "Name", "Marks");
std::println(out, "{:<8}{:>5}", "Asha", 78);
std::println(out, "{:<8}{:>5}", "Ravi", 91);
out.close();
// Copy a whole file in one statement through its stream buffer
{
std::ifstream src("marks.txt", std::ios::binary);
std::ofstream dst("marks_backup.txt", std::ios::binary);
dst << src.rdbuf();
}
std::ifstream in("marks_backup.txt");
std::string line;
while (std::getline(in, line)) std::cout << line << '\n';
}Output:
Name Marks
Asha 78
Ravi 91For a simple copy you can also call std::filesystem::copy_file(from, to), which lets the operating system do the work.
C++ Streams vs C File Functions
You may have used fopen, fprintf, fscanf and fclose in C. They still work in C++ (header <cstdio>), but C++ streams have clear advantages:
C (FILE*) | C++ (fstream) | |
|---|---|---|
| Closing | Manual fclose; easy to leak | Automatic (RAII) |
| Type safety | Format string must match types (%d, %s); mismatches are undefined behaviour | <</>> chosen by the compiler from the type |
| User-defined types | Not supported | Overload operator<< / operator>> (see Operator Overloading) |
| Same code for console, file, string | Partly | Yes, via istream& / ostream& |
| Raw speed | Usually fast | Comparable; formatted >> can be slower |
Common Mistakes
1. Not checking whether the file opened
A misspelled name or wrong working directory gives a failed stream, and every read then silently does nothing. Always check if (!file) right after opening.
2. Looping with while (!file.eof())
Processes the last item twice or processes garbage. Loop on the read itself: while (file >> x) or while (std::getline(file, line)).
3. Accidentally truncating a file
Opening an existing file with plain std::ofstream erases it. Use std::ios::app to add to it.
4. Mixing >> and getline
After file >> n, the newline is still in the stream, so the next getline returns an empty string. Use file >> std::ws or file.ignore(...) before getline, exactly as with cin in Input & Output.
5. Writing objects with pointers to binary files
Writing a struct containing std::string, std::vector or any pointer with write saves addresses, not data. Reading it back is undefined behaviour.
6. Forgetting std::ios::binary for binary data
Works on Linux, then corrupts data on Windows because of newline translation.
7. Forgetting that a failed stream stays failed
After a read error, call clear() before reading again, and before seeking back to the start to re-read a file that hit the end.
Interview / Exam Questions
Q1. What is the difference between ifstream, ofstream and fstream?
ifstream is an input file stream (derived from istream) for reading; ofstream is an output file stream (derived from ostream) for writing; fstream (derived from iostream) supports both. Their default open modes are in, out and in | out respectively.
Q2. What is the difference between ios::app and ios::ate?
With app, every write is performed at the end of the file, no matter where you seek. With ate, the position is placed at the end once, right after opening, and you are free to seek elsewhere and write there.
Q3. Why is while (!in.eof()) wrong for reading a file?
eof() becomes true only after a read has tried to go beyond the end. After the last item has been read successfully, eof() is usually still false, so the loop runs once more; that read fails, and the loop body uses a stale or invalid value. The correct pattern tests the read operation itself: while (in >> x).
Q4. A binary file contains fixed-size records of type Rec. How do you read the 10th record without reading the first nine?
Open it with std::ios::binary, call in.seekg(9 * sizeof(Rec)) (records are numbered from 0), then in.read(reinterpret_cast<char*>(&r), sizeof(Rec)).
Q5. Why can't you write a struct containing a std::string to a binary file with write()?
A std::string object usually contains a pointer to characters stored elsewhere on the heap (except short strings kept inside the object). write copies the raw bytes of the struct, i.e. the pointer value, not the characters. Read back in another run, that pointer is meaningless. Only trivially copyable types without pointers can be saved this way; strings must be serialized explicitly (for example, length followed by characters).
Q6. How do you get the size of a file in C++?
Either open it with std::ios::binary | std::ios::ate and call tellg(), or (C++17) call std::filesystem::file_size(path).
Summary
<fstream>givesifstream,ofstreamandfstream; they behave likecin/coutand close automatically (RAII).Always check that a file opened, and loop on the read operation itself, never on
eof().Open modes:
in,out(truncates),app,ate,trunc,binary, and C++23noreplace.Use
getline+stringstreamto parse line-based formats like CSV, and handle bad data.Binary I/O uses
read/writeon trivially copyable types;seekg/seekp/tellggive random access to fixed-size records.Stream flags
good,eof,fail,badexplain what went wrong;clear()resets them;exceptions()makes streams throw.std::filesystem(C++17) manages files and directories; C++23'sstd::printlnwrites formatted text to files.
As programs grow, names like Record, report or print start to clash between different parts of the code. In the next chapter, Namespaces, we see how C++ organizes names, and what std:: and namespace fs = std::filesystem; really mean.