Lesson 31 / 36
Reading & Writing Files
fprintf/fscanf for text, fread/fwrite for raw bytes.
Read a text file line by line
fgets returns NULL at end-of-file, which doubles as the loop condition.
FILE *fp = fopen("notes.txt", "r");
if (fp == NULL) { perror("open"); return 1; }
char line[100];
while (fgets(line, sizeof(line), fp) != NULL) {
printf("%s", line);
}
fclose(fp);fwrite / fread for raw data
Binary mode reads/writes exact byte layouts — useful for structs, not just text.
struct Point { int x, y; } p = {3, 4};
FILE *fp = fopen("point.bin", "wb");
fwrite(&p, sizeof(p), 1, fp);
fclose(fp);
struct Point q;
fp = fopen("point.bin", "rb");
fread(&q, sizeof(q), 1, fp);
fclose(fp);
printf("%d,%d\n", q.x, q.y);
Output:
3,4
Quick check: What does fopen return if the file cannot be opened?
- NULL
- An empty string
- It crashes the program
Answer
NULL — fopen returns NULL on failure -- always check before using the handle.