Reading Files
File I/O in C runs through FILE pointers and the helpers in <stdio.h>. Pattern's always the same: open, read or write, close.
Opening a File
FILE *fp = fopen("data.txt", "r");if (fp == NULL) { perror("Failed to open file"); return 1;}The second argument is the mode: "r" for reading, "w" for writing (truncates), "a" for appending, "rb" for reading binary.
Reading Line by Line
char line[256];while (fgets(line, sizeof(line), fp) != NULL) { printf("%s", line);}fgets reads up to sizeof(line) - 1 characters, stopping early if it hits a newline. The buffer's always null-terminated when it returns.
That "up to" matters. A line longer than the buffer arrives in pieces, and the only clue is that the piece doesn't end in '\n'. The runner writes a small file with one deliberately long line, reads it back through a 16-byte buffer, then uses feof and ferror to say why the loop stopped.
The last line is a trap: it's complete but has no newline, because the file simply ended. That's why the check at the bottom matters. fgets returns NULL both at end of file and on a read error, and only feof and ferror can tell you which one you got.
Worked Example: The Runner, Call by Call
Here's every fgets call the runner makes, with the file position afterwards (what ftell(fp) reports). The buffer holds 16 bytes, so each call can take at most 15 characters and still leave room for the '\0':
| Call | Bytes copied into buf | Length | Ends in '\n'? | Position after |
|---|---|---|---|---|
| 1 | short\n | 6 | yes | 6 |
| 2 | this line is mu | 15 | no | 21 |
| 3 | ch longer than | 15 | no | 36 |
| 4 | sixteen bytes\n | 14 | yes | 50 |
| 5 | no newline at t | 15 | no | 65 |
| 6 | he end | 6 | no | 71 |
| 7 | nothing: returns NULL | 71 |
Calls 2 and 3 stop because the buffer is full, and the next call carries on exactly where the last one left off; nothing is skipped or lost. Call 4 finds the newline and stops after it. Call 6 stops because the file ran out, which is why its piece has no newline even though it's the end of a line. Call 7 has nothing left to read, returns NULL and sets the end-of-file indicator, so feof(fp) is now true.
Reading Formatted Data
int age;char name[50];fscanf(fp, "%49s %d", name, &age);Always limit the width in fscanf string specifiers (like %49s) to prevent buffer overflows. An unbounded %s will write past the end of your buffer if the input is too long.
The other half of using fscanf safely is checking what it returns: the number of items it matched and stored, or EOF if input ran out before the first one. Suppose the file holds alice 30, then bob thirty. On the second record %49s happily reads bob, %d fails on t, and fscanf returns 1. A loop that only tests for EOF would carry on with name set to bob and age still holding Alice's 30. Worse, thirty was never consumed, so the next call reads it as a name and reports a third person, also aged 30:
// Wrong: prints bob 30 and thirty 30 as if they were real recordswhile (fscanf(fp, "%49s %d", name, &age) != EOF) { ... }
// Right: only a fully parsed record countsint n;while ((n = fscanf(fp, "%49s %d", name, &age)) == 2) { printf("%s is %d\n", name, age);}if (n != EOF) fprintf(stderr, "malformed record starting %s\n", name);For anything less trivial, read whole lines with fgets and parse each with sscanf. A bad line then can't wedge the stream, and you can report which line it was.
Reading Characters
int ch;while ((ch = fgetc(fp)) != EOF) { // process character}Why while (!feof(fp)) Is Wrong
Many first attempts at a read loop look like this:
char line[64];while (!feof(fp)) { fgets(line, sizeof line, fp); printf("got: %s", line);}Predict: the file contains apple and banana, each followed by a newline. What does this loop print?
got: applegot: bananagot: bananafeof doesn't look ahead. It only reports that an earlier read already ran into the end of the file. After the second fgets the position sits at the very end, but no read has tried to go past it yet, so feof is still false and the loop goes round again. That third fgets finds nothing, returns NULL and leaves line holding banana from last time, which gets printed a second time.
The fix is the pattern from the top of this lesson: make the read itself the loop condition, as in while (fgets(...) != NULL) or while ((ch = fgetc(fp)) != EOF). Save feof and ferror for after the loop, to find out why it stopped.
Closing Files
Always close files when done:
fclose(fp);Skip the close and you risk two things: lost writes from unflushed buffers, and a slow leak of file descriptors. The OS caps how many a process can hold open. Long-running programs that leak handles will eventually see fopen start failing.