Files — Data That Outlives the Program

← Course home · ← Strings module · Unit 12/16 · Syllabus

Every program you have written had one sad property: when it ended, its data vanished. A roster of 30 students, a ledger of 200 expenses — gone at exit, rebuilt by hand tomorrow. Files fix this: variables live in memory while the program runs; files live on disk between runs. This unit connects the two with streams — ifstream to read, ofstream to write — and teaches the discipline that keeps file programs honest: open, check, use, close, and read until the data runs out.

Everything you know transfers. cin/cout taught you streams in Unit 03; a file stream is the same idea pointed at a file. getline taught you line reading; file getline is the same function with a stream swap. Records taught you schemas; a file is just a schema written as text, line by line.

In this module you will learn

Module map

Page What’s inside
Lesson 1 — Streams: writing and reading files persistence, ofstream/ifstream/fstream, open-check-close, the first full examples
Lesson 2 — Reading strategies and file formats modes & append, line-based vs formatted reading, CSV files, record storage
Lesson 3 — File errors and the mistakes gallery basic file errors, the EOF discipline, ten seeded mistakes, the complete program
Exercises 18 exercises with separated solutions (S1–S18)
Debugging 10 seeded file bugs
Challenges 10 challenges with separated solutions
Labs 6 file labs — student records, expenses, inventory, marks report, contacts, transaction log
Mini-project The File-Based Student Management System

Try it yourself first

Same rule as every module: attempt 15 minutes before opening any solution — with the file habit: before writing any file code, write the file’s first two lines by hand (in an editor, as literal text). If you can’t write the exact format your program will read, your schema isn’t decided yet. Files make formats contracts — the writer and reader must agree character for character.

⚠️ Safety rules for this unit

Files can’t crash your program the way pointers can — but they can destroy your data silently. The unit’s non-negotiables:

  1. Check every open. is_open() before any use, on reading and writing streams — silent failure is the enemy.
  2. Say what your open means. A plain ofstream erases the file; std::ios::app appends. There is no undo.
  3. Put the read in the loop condition. while (getline(in, line)) — never while (!in.eof()).
  4. End every field write with its separator. A format without separators is soup.
  5. Never destroy the only copy. Rewrite pipelines back up first (or write-to-temp); append-only logs stay append-only.

Pacing

Unit 12 spans one week (2 sessions):

What comes next

Files close Stage D’s toolkit: Unit 15 adds classes and vectors — the Student Management System you build here becomes a class in the OOP mini-project, and its file code barely changes (the format is the contract, and contracts survive refactors).

Checklist