Skip to content

Module 7 · Templates, Exceptions, Namespaces and Files — topic 4 of 4

File Handling

Read and write files with ifstream, ofstream and fstream: text lines, formatted values, CSV parsing, append mode, binary data and error checking.

Beginner 15 min read·Lesson 30 of 40 in C++ Programming

Learning objectives

  • Write and read text files with streams
  • Parse CSV lines with stringstream
  • Use append and binary modes and check for errors

Definition

C++ file I/O uses stream classes from <fstream>: std::ifstream for input, std::ofstream for output and std::fstream for both. They support the same >>, << and getline operations as console streams and close automatically when destroyed.

Introduction

File streams behave just like std::cin and std::cout, so everything you know about stream operators applies. And because they are RAII objects, the file closes automatically at the end of the scope — no fclose to forget.

Why it matters

Every management-system project stores data in files.

Parsing CSV and log files is an everyday programming task.

Detailed explanation

std::ofstream out("data.txt"); creates or truncates; std::ios::app appends; std::ios::binary disables newline translation.

Check success with if (!in) or in.is_open(). After reading fails, the stream is in a fail state; reading loops test the read itself: while (std::getline(in, line)).

std::istringstream turns a line into a stream so you can split fields with getline(ss, field, ',').

Binary I/O: out.write(reinterpret_cast<const char*>(&value), sizeof value) and in.read(...) — only for trivially copyable types and with portability caveats.

std::filesystem (C++17) checks existence, sizes and directories: std::filesystem::exists("data.txt").

Syntax

C++
std::ofstream out("marks.csv");
out << "Asha,92\n";
out.close(); // or let it go out of scope
std::ifstream in("marks.csv");
std::string line;
while (std::getline(in, line)) {
std::istringstream ss(line);
std::string name, mark;
std::getline(ss, name, ',');
std::getline(ss, mark);
}
  • Include <fstream> and <sstream>.
  • Never loop on eof(); test the read operation.
  • Streams close in their destructors.

Code examples

Write then read lines

C++
#include <fstream>
#include <iostream>
#include <string>
int main() {
{
std::ofstream out("topics.txt");
out << "Classes\nTemplates\nSTL\n";
} // file closed here
std::ifstream in("topics.txt");
std::string line;
int n = 0;
while (std::getline(in, line)) std::cout << ++n << ". " << line << '\n';
return 0;
}
Output
1. Classes
2. Templates
3. STL

Handling a missing file

C++
#include <fstream>
#include <iostream>
int main() {
std::ifstream in("missing.txt");
if (!in) {
std::cout << "could not open missing.txt\n";
return 0;
}
return 0;
}
Output
could not open missing.txt

More examples

Parsing a CSV and appending results

C++
#include <fstream>
#include <iomanip>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
struct Row { std::string name; int marks; };
int main() {
std::ofstream("marks.csv") << "name,marks\nAsha,92\nRavi,67\nMeera,85\n";
std::ifstream in("marks.csv");
std::string line;
std::getline(in, line); // skip header
std::vector<Row> rows;
while (std::getline(in, line)) {
std::istringstream ss(line);
std::string name, marks;
if (std::getline(ss, name, ',') && std::getline(ss, marks)) rows.push_back({name, std::stoi(marks)});
}
double total = 0;
for (const auto& r : rows) total += r.marks;
std::ofstream log("report.txt", std::ios::app);
log << rows.size() << " students, average " << total / rows.size() << '\n';
log.close();
std::ifstream report("report.txt");
std::cout << report.rdbuf();
std::cout << std::fixed << std::setprecision(1) << "average: " << total / rows.size() << '\n';
return 0;
}
Output
3 students, average 81.3333
average: 81.3

Step-by-step explanation

  • A temporary std::ofstream writes the CSV and closes at the end of the statement.
  • The header line is skipped before parsing rows.
  • istringstream splits each row at the comma; stoi converts marks.
  • The report is opened in append mode; rdbuf() prints a whole file.

Expected output

Running “Parsing a CSV and appending results” prints exactly:

TextOutput
3 students, average 81.3333
average: 81.3

Practical applications

  • Configuration loaders read key=value files.
  • Data pipelines import and export CSV.
  • Applications append to log files.

Best practices

  • Check that every file opened successfully.
  • Let RAII close files; keep stream scopes small.
  • Prefer text formats for portability; document binary layouts.

Common mistakes

Looping on eof()

Avoid

while (!in.eof()) { std::getline(in, line); process(line); }

Prefer

while (std::getline(in, line)) { process(line); }

eof() becomes true only after a failed read, so the last line is processed twice.

Truncating a file you meant to extend

Avoid

std::ofstream log("app.log");

Prefer

std::ofstream log("app.log", std::ios::app);

The default mode for ofstream truncates existing content.

Important notes

  • Relative paths are resolved from the current working directory, not the executable's folder.
  • Binary-writing structs is not portable across compilers or architectures.

Key takeaways

  • ifstream reads, ofstream writes, fstream does both.
  • Loop on getline; never on eof().
  • Use std::ios::app to append.

Try it yourself

  1. 1
    Count lines, words and characters in a file given on the command line.
  2. 2
    Write a vector of structs to CSV and read it back into a new vector.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

4 questions test this exact topic. Answers and explanations are revealed after you submit.

  • BeginnerWhich class reads from a file?
  • BeginnerWhy does `while (!in.eof()) { std::getline(in, line); process(line); }` process the last line twice?
  • ModerateWhich open mode adds data to the end of an existing file?
Practise this topic