Intermediate⏱️ 9 min📘 Topic 29 of 32

📂 File Handling in C++ — Read, Write and Append with fstream

Master file handling in C++ using fstream — read files line by line, write to files, append, check open success, and handle binary vs text mode with examples.

C++ file I/O uses the <fstream> header. Three stream classes:

  • std::ofstream — output (write)
  • std::ifstream — input (read)
  • std::fstream — both read AND write

✍️ Writing to a file

#include <fstream>
std::ofstream out("data.txt");
out << "Hello\n";
out << 42 << '\n';
out.close();

📖 Reading from a file

std::ifstream in("data.txt");
std::string line;
while (std::getline(in, line)) {
  std::cout << line << '\n';
}

➕ Append mode

std::ofstream out("log.txt", std::ios::app);
out << "new entry\n";

🔍 Check if open succeeded

std::ifstream in("missing.txt");
if (!in.is_open()) {
  std::cerr << "can't open file";
  return 1;
}

💾 Binary mode

Use std::ios::binary to avoid newline translation on Windows. Required for images, binary data structures, etc.

💻 Code Examples

Write then read

#include <fstream>
#include <string>
#include <iostream>
int main() {
  std::ofstream out("hello.txt");
  out << "Hello, file!\n" << "Line 2";
  out.close();

  std::ifstream in("hello.txt");
  std::string line;
  while (std::getline(in, line)) std::cout << line << '\n';
}
Output:
Hello, file!
Line 2

Append safely

std::ofstream log("events.log", std::ios::app);
if (log) log << "[INFO] User logged in\n";
Output:
Adds a new line without overwriting existing content.

⚠️ Common Mistakes

  • Not checking `is_open()` — silently writes nothing or reads nothing when the file is missing.
  • Opening for write (default) when you meant to append — truncates the existing file.
  • Forgetting binary mode for non-text data — Windows mangles newlines.
  • Reading past end-of-file without checking — `while (!in.eof())` is the wrong pattern; use the read operation itself as the condition.

🎯 Interview Questions

Real questions asked at top product and service-based companies.

Q1.Which header do you need for file I/O in C++?Beginner
`<fstream>`. It provides ifstream (read), ofstream (write), and fstream (both).
Q2.How do you read a file line by line?Beginner
Use std::getline in a loop: `while (std::getline(in, line)) { ... }`. The condition is true while a line is successfully read.
Q3.How do you append to a file instead of overwriting?Intermediate
Open with the `std::ios::app` flag: `std::ofstream out("file", std::ios::app);`. Without it, opening for write truncates the file.
Q4.What's the difference between text mode and binary mode?Intermediate
Text mode (default) translates newlines (e.g., \n ↔ \r\n on Windows). Binary mode reads/writes raw bytes — required for images, audio, packed binary structs, anything non-text.
Q5.Why is `while (!in.eof())` a bad idea?Advanced
eof() only becomes true AFTER a failed read attempt. The loop body executes ONCE with invalid data before exiting. Correct: use the read operation itself as the condition.

🧠 Quick Summary

  • <fstream> — ifstream (read), ofstream (write), fstream (both).
  • Use std::getline for line-by-line reading.
  • std::ios::app for append; std::ios::binary for raw data.
  • Always check is_open() after opening.
  • Don't use while (!eof()) — check the read operation directly.