C++ - Files & I/O

Overview

Estimated time: 45–65 minutes

Read and write files using iostreams for text and binary data. Use std::filesystem for path-safe operations and follow robust patterns for error handling.

Learning Objectives

  • Open, read, and write text files with RAII (std::ifstream/std::ofstream).
  • Perform simple binary I/O and understand stream modes.
  • Use std::filesystem::path for portable path manipulation.

Prerequisites

Write and read a text file

#include <fstream>
#include <string>
#include <iostream>
int main(){
  {
    std::ofstream out("example.txt");
    if (!out) { std::cerr << "open failed\n"; return 1; }
    out << "hello\n" << "world\n";
  }
  std::ifstream in("example.txt");
  if (!in) { std::cerr << "open failed\n"; return 1; }
  std::string line;
  while (std::getline(in, line)) std::cout << line << "\n";
}

Expected Output: hello world

Read entire file into a string

#include <fstream>
#include <string>
#include <iterator>
#include <iostream>
int main(){
  std::ifstream in("example.txt");
  std::string content((std::istreambuf_iterator<char>(in)), std::istreambuf_iterator<char>());
  std::cout << content;
}

Binary I/O

#include <fstream>
#include <iostream>
int main(){
  {
    std::ofstream out("data.bin", std::ios::binary);
    int v = 0x12345678;
    out.write(reinterpret_cast<const char*>(&v), sizeof(v));
  }
  std::ifstream in("data.bin", std::ios::binary);
  int x = 0;
  in.read(reinterpret_cast<char*>(&x), sizeof(x));
  std::cout << std::hex << x << "\n";
}

Expected Output (example): 12345678

filesystem::path (C++17)

#include <filesystem>
#include <iostream>
int main(){
  std::filesystem::path dir = "data";
  std::filesystem::path file = dir / "log.txt";
  std::cout << file.string() << "\n";
}

Beginner Boosters

#include <fstream>
#include <iostream>
int main(){
  std::ofstream out("numbers.txt");
  for (int i=1;i<=3;++i) out << i << "\n";
  std::ifstream in("numbers.txt"); int x{}; int sum=0; while (in>>x) sum+=x; std::cout << sum << "\n"; // 6
}

Common Pitfalls

  • Not checking stream state after opening/reading/writing.
  • Forgetting std::ios::binary on binary files (especially on Windows).
  • Using hard-coded path separators; prefer std::filesystem::path / operator.

Checks for Understanding

  1. How do you read a text file line by line?
  2. When should you use std::ios::binary?
Show answers
  1. Open std::ifstream and use std::getline in a loop.
  2. When reading/writing non-text (binary) data to avoid newline translation.

Exercises

  1. Copy a file line-by-line to another file; handle open errors.
  2. Write a small binary struct to disk and read it back; verify field values.