cadence_learn
the_c++_track / level 12 of 15 ▶ 15 min

make it survive.

Files are cout and cin pointed somewhere that lasts. The only new thing is that the other end can be missing — and C++ will not raise its voice about it.

after this level you'll be able to
  • Write data to a file and read it back
  • Check whether a file actually opened, and say why that matters
  • Read a file of unknown length without counting anything
the same arrows

cout and cin, pointed at a file

Everything your programs have done so far has vanished when they stopped. Files are how work survives — and there is almost nothing new to learn, because the arrows are the ones you already know.

open, use, close — in both directions
WRITING — ofstream ofstream out("scores.txt"); out << 42 << endl; out.close(); same << arrows as cout scores.txt on the disk survives the program READING — ifstream ifstream in("scores.txt"); in >> score; in.close(); same >> arrows as cin IF THE FILE IS NOT THERE, ifstream DOES NOT CRASH AND DOES NOT TELL YOU. It opens “unsuccessfully”, every read does nothing, and your program prints zeroes as if it had real data. Verified: is_open() came back 0. Three steps either way: openuseclose — and the arrows are the ones you already know.
Files are just cout and cin pointed somewhere else. The only genuinely new thing is that the other end can be missing — and C++ will not raise its voice about it.
#include <fstream> ofstream out("scores.txt"); // o for OUT — writing out << 42 << endl; // exactly like cout out.close(); ifstream in("scores.txt"); // i for IN — reading int score; in >> score; // exactly like cin in.close();

Open, use, close. The o and i at the front tell you which direction, and the arrows match — out to the file with <<, in from the file with >>.

◈ ask an ai about this

“How do I read from and write to a file in C++? Explain ifstream and ofstream simply.”

chatgpt ↗ claude ↗

try it yourself

write it, then read it back

▤ lab 11 · the file

Watch the disk panel. Then try reading a file that was never written.

THE DISK
scores.txt

        
program output
# nothing yet
Run the writer first, then the reader. Then delete the file and read again.
the failure that stays silent

A missing file does not crash your program and does not print an error. ifstream simply opens unsuccessfully, every read does nothing at all, and your variables keep whatever they already had — often zero. Your program then reports a perfectly confident total of 0. Verified: is_open() returned 0 and nothing else happened.

So check, every time. It is two lines:

ifstream in("scores.txt"); if (!in) { cout << "Could not open scores.txt" << endl; return 1; // not 0 — 0 means it went fine (level 2) }
◈ ask an ai about this

“How do I check whether a file opened in C++, and how do I read it until the end without knowing its length?”

chatgpt ↗ claude ↗

the shape

reading until it runs out

You almost never know how many lines a file has. So you do not count — you read until reading stops working, which is a while from level 7 with the read itself as the condition:

string line; while (getline(in, line)) { cout << line << endl; }

That reads as “while there is another line to get, get it”. For numbers rather than lines, while (in >> number) does the same job. Both stop cleanly at the end of the file, and both stop immediately if the file never opened — which is precisely why the check above matters: without it, an unopened file and an empty file look identical.

where the file actually is

"scores.txt" with no path means the folder your program is running in, which is wherever your Terminal was when you typed ./program — not necessarily where the file is saved. “It cannot find my file” is almost always this, and ls from level 1 settles it in one command.

do this together

hand-write the file

☶ two people · 15 minutes · one sheet of paper as the disk

One writes to the paper. One reads it back, blind.

person a — the writer

Decide a format and write five records on the paper. Names and scores, one per line? Comma separated? You choose — but do not say which.

person b — the reader

Work out the format from the paper alone, then say exactly which C++ reads it: getline, or in >> name >> score?

The argument that follows is the real lesson: a name with a space in it breaks in >> name, and a comma-separated line breaks it too. Whoever wrote the file decided how hard it is to read, and they usually did not think about it. That is most of what working with real data is.

what to keep

three things worth remembering

01

Open, use, close

ofstream out, ifstream in, and the same arrows you already know.

02

Always check it opened

A missing file is silent. Without the check, no data and empty data look the same.

03

Read until it stops

while (getline(in, line)). Do not count lines you have not seen.

check yourself

3 questions before you move on

Not recall — these are the shapes an exam actually uses. Every answer below was produced by compiling and running the code, so if you disagree with one, the compiler is the one to believe.

▢ check yourself3 questions

Have a real go before revealing. Being wrong here is worth more than being right in three weeks.

01

You read a file that does not exist. What does your program do?

02

How do you read a file when you do not know how many lines it has?

03

Your program cannot find scores.txt, but you can see the file on your desktop. Why?

answered: 0 of 3right first time: 0
Stuck? Peter reads these personally and replies to your email.
Ask Peter →