Reading and Writing Text Files
fgetc, fputc, fgets, fprintf, and fscanf, with end-of-file handled correctly.
Working the Stream
Opening and closing frames the work; this lesson is the work: writing structured text into files and parsing it back out, with the loops and guards you already own aimed at streams. Nothing here is new machinery, the f-family plus chapter 6's sentinel loops cover everything, and that transfer is the lesson.
Writing Structured Text
fprintf is printf with a destination, format language intact:
One value per line is the simplest file format that exists, and worth taking seriously: formats are contracts between the writer and the reader, and the reading code below works because it knows exactly this shape. Width and precision specifiers align columns in files exactly as they did on screen in chapter 4.
Reading Until the File Ends
fscanf returns the same conversion count scanf always did, with EOF at stream's end, so the sentinel loop transfers verbatim:
while (fscanf(...) == 1) reads numbers until anything other than a clean conversion, end of file or malformed content, ends the loop: chapter 6's guarded sentinel, now consuming a file. The same distinction from chapter 4 applies at the end: the loop cannot tell "ran out of file" from "hit a bad token" by the count alone, and programs that must distinguish them ask feof(in) afterwards, the one new function this lesson needs.
Character- and line-level reading transfer identically: fgetc until EOF is the chapter 4 copy loop with streams for both ends, and fgets until NULL processes a file line by line, the shape that dominates real text tooling:
while (fgets(line, CAPACITY, in) != NULL) {
/* one line, newline included, per pass */
}
The Copy Program
The file world's canonical program combines one read loop and one write call, and exams love it whole:
Every piece is a veteran: int ch for EOF's sake, the assign-and-test loop with its precedence parentheses, and a failure branch that closes whichever stream did open, the per-path cleanup rule earning its keep with two resources. (getc/putc are the traditional spellings of fgetc/fputc; both appear in real code and exams.)
Text Files Are Just Bytes You Agreed About
A "text file" has no special machinery: it is bytes that writer and reader agree to treat as lines of characters. That agreement is why mixing tools works, your program writes, an editor reads, and why sloppy formats rot: a reader expecting %d %d per line breaks the day a third column appears. The professional habits in miniature: write a format you would want to parse, read it with the same guards you give keyboard input, and remember the file does not care, only the programs on each end do. Binary files, next lesson, are the other agreement about the same bytes.
Key Takeaways
fprintfwrites formatted text to a stream; the format is a contract the reading code depends on.while (fscanf(in, "%d", &v) == 1)is the file sentinel loop;feofdistinguishes clean end from bad content when it matters.fgetc/getcuntil EOF andfgetsuntil NULL transfer the chapter 4 and 8 loops to files unchanged.- The copy program: one EOF loop,
putcper character, and failure handling that closes whichever stream opened. - Text files are bytes both sides agree to read as characters; design formats you would want to parse.
How did you find this lesson?
Your rating helps us improve the content.
Create an account to track your progress and access interactive exercises. Already have one? Sign in.
Reading and Writing Text Files - Quiz
Test your understanding of the lesson.
Practice Exercises
Write, Reopen, Sum
Read a count and that many integers from standard input, write them one per line to /tmp/data.txt, close it, reopen for reading, and sum them back with the fscanf sentinel loop. Report the count read from disk and the total.
Lesson Discussion
Share your thoughts and questions
No comments yet. Be the first to share your thoughts!