Skip to main content

Reading and Writing Files

beginner14 min readLesson 59 of 148

fgets/fputs for lines, fprintf/fscanf for formatted data, feof/EOF for the end.

Writing text

FILE *f = fopen("log.txt", "w");
if (f == NULL) return 1;
fprintf(f, "score=%d\n", 42);
fputs("plain line\n", f);
fclose(f);

Reading line by line

char line[128];
FILE *f = fopen("log.txt", "r");
if (f == NULL) return 1;
while (fgets(line, sizeof line, f) != NULL) {
    // line includes the trailing '\n' (when it fits)
    fputs(line, stdout);
}
fclose(f);

fgets returns NULL at end-of-file or error โ€” that is the loop condition. The buffer size is respected: no overflow.

Parsing what you read

int score;
if (sscanf(line, "score=%d", &score) == 1) {
    // matched exactly one conversion
}

Check sscanf's return value โ€” it counts successful conversions.

The EOF family

  • fgets returning NULL: the line loop's end signal
  • feof(f): true AFTER a read hit end-of-file โ€” never loop on feof alone
  • ferror(f): true if an I/O error occurred

The pattern for persistence

write โ†’ fclose โ†’ fopen("r") โ†’ read โ†’ fclose. Closing on write flushes the data; reopening for read sees it. You will use exactly this in the practice: write a small log, then read it back and count.

Now practice

File WorkbenchWrite, read back, append, and count โ€” real files under /tmp.3 challenges ยท ยท ~18 minPersistence LayerSave records to a file and load them back โ€” the seed of every stored-data app.3 challenges ยท ยท ~18 min