Unit 3 · Lesson 228 minAcademic review pending

Persist readable data with text files

Open, read, write, append, close, and diagnose text-file operations through FILE streams.

Choose explanation

After this lesson

You should be able to

  • Choose a file mode and check every operation that can fail.
  • Read a text file line by line without relying on end-of-file guesses.
01

A FILE pointer represents a stream

fopen returns a FILE pointer or null on failure. Mode "r" reads an existing file, "w" creates or truncates, and "a" creates or appends. Add + for update modes. Choose deliberately: opening valuable data with "w" destroys its previous contents.

Close every successfully opened stream with fclose and check important writes. perror can report the operating-system reason associated with a failed library call.

Append one result
FILE *file = fopen("scores.txt", "a");
if (file == NULL) {
    perror("scores.txt");
    return 1;
}

if (fprintf(file, "%d %.1f\n", roll, score) < 0) {
    fprintf(stderr, "Could not write score\n");
}

fclose(file);
02

Read while reading succeeds

Do not write while (!feof(file)). End-of-file becomes known only after a read attempts to pass it, so that pattern may process stale data. Put the read operation in the loop condition.

fgets reads a bounded line and preserves spaces. fscanf can parse structured tokens, but malformed input must be handled by checking the conversion count. Text formats remain readable but require an explicit parsing contract.

Line-by-line read
char line[256];

while (fgets(line, sizeof line, file) != NULL) {
    fputs(line, stdout);
}

if (ferror(file)) {
    perror("read");
}

Try it yourself

Choose the mode for adding new log lines without removing existing ones.

Need a hint?

The word is append.

Check the worked solution

Use "a" for write-only append or "a+" when reading is also required.

Quick check

Why is while (!feof(file)) usually wrong?

Select an answer to check your thinking.

Why this lesson exists

Syllabus mapping

Text files · Creating, reading, writing, and appending files

Maps to course outcomes CO3, CO4.