Skip to main content
Be Bitwise
CFile I/O

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

c
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

c
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.

Try itRun it, then grow buf to 64 bytes and watch the long line arrive in one piece.
C (GCC 9.2.0)

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':

CallBytes copied into bufLengthEnds in '\n'?Position after
1short\n6yes6
2this line is mu15no21
3ch longer than 15no36
4sixteen bytes\n14yes50
5no newline at t15no65
6he end6no71
7nothing: returns NULL71

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

c
int age;
char name[50];
fscanf(fp, "%49s %d", name, &age);
Key Concept

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:

c
// Wrong: prints bob 30 and thirty 30 as if they were real records
while (fscanf(fp, "%49s %d", name, &age) != EOF) { ... }
// Right: only a fully parsed record counts
int 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

c
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:

c
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?
c
got: apple
got: banana
got: banana

feof 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:

c
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.