Show contents
Chapter 1 of 6 · 20 min
Reading and writing files
By the end of this chapter, you'll be able to
- Open a file with fopen and check the result
- Write with fprintf and fputs, read line by line with fgets
- Extract values from a line with sscanf, checking its return value
- Close every file with fclose and report errors with perror
Open, write, read back
fopen(name, mode), from <stdio.h>, opens a file and returns a FILE * pointer, or NULL on failure. The modes are the same as in Python: "r" (read), "w" (write, the file is emptied), "a" (append at the end).
#include <stdio.h>
int main(void) {
const char *name = "readings.txt";
FILE *f = fopen(name, "w");
if (f == NULL) {
perror(name);
return 1;
}
fprintf(f, "Bamako 38\n");
fprintf(f, "Oslo -3\n");
fprintf(f, "Lima 19\n");
fclose(f);
f = fopen(name, "r");
if (f == NULL) {
perror(name);
return 1;
}
char line[64];
int number = 0;
while (fgets(line, sizeof line, f) != NULL) {
char city[32];
int temperature;
number++;
if (sscanf(line, "%31s %d", city, &temperature) == 2) {
printf("%d. %s: %d °C\n", number, city, temperature);
}
}
fclose(f);
remove(name);
return 0;
}
1. Bamako: 38 °C
2. Oslo: -3 °C
3. Lima: 19 °C
fprintf(f, …)works likeprintf, but writes to the file.fputs(text, f)writes a string as is.fgets(line, size, f)reads one line, never more thansize - 1characters, and adds the final'\0'. The'\n'is kept. It returnsNULLat the end of the file.sscanfreads values from a string, asscanfdoes from the keyboard. It returns the number of values read: we check that it's 2.%31slimits reading to 31 characters: with the'\0', that fits incity[32]. Without this limit, a name that's too long would overflow the array.perror(name)displays the name followed by the reason for the failure given by the system, for examplereadings.txt: Permission denied.remove(name)deletes the file: we use it here so that the example leaves nothing behind.
After the third line, there's nothing left to read: fgets returns NULL and the loop stops.
Text description of the animation
- The file contains three lines. f points to its start.
- fgets reads the first line, '\n' included, and stores it in the array line.
- sscanf extracts two values: a word and an integer. It returns 2, the condition is true.
- The line is displayed.
- Second pass: fgets resumes where it stopped.
- After the third line, there's nothing left to read: fgets returns NULL and the loop stops.
Why close with fclose
To be efficient, fprintf doesn't write straight to the disk: the text builds up in a buffer in memory, flushed from time to time. fclose flushes this buffer then releases the file. A program that forgets fclose, or stops abruptly, can lose its last lines. Also, the system limits how many files can be open at once: a program that forgets to close them ends up unable to open any more.
Your turn
Worked exercise
Worked exercise: the average of a grades file
Your program first writes a file grades.txt containing "first-name grade" lines: Awa 15.5, Kenji abc, Lina 12, an empty line, then Tomas 9. Read it back and display the number of valid grades, their average with two decimals, and the number of non-empty lines skipped because they're invalid. Expected output: 3 grades, average 12.17, 1 line(s) skipped.
Hint 1
sscanf(line, "%31s %lf", name, &grade) returns 2 only if both values were read. Careful: a double is read with %lf.Hint 2
'\n': test line[0] != '\n' so as not to count it as invalid.Show the solution and common mistakes
#include <stdio.h>
int main(void) {
FILE *f = fopen("grades.txt", "w");
if (f == NULL) {
perror("grades.txt");
return 1;
}
fputs("Awa 15.5\nKenji abc\nLina 12\n\nTomas 9\n", f);
fclose(f);
f = fopen("grades.txt", "r");
if (f == NULL) {
perror("grades.txt");
return 1;
}
char line[80];
double sum = 0;
int valid = 0, skipped = 0;
while (fgets(line, sizeof line, f) != NULL) {
char name[32];
double grade;
if (sscanf(line, "%31s %lf", name, &grade) == 2) {
sum += grade;
valid++;
} else if (line[0] != '\n') {
skipped++;
}
}
fclose(f);
remove("grades.txt");
printf("%d grades, average %.2f, %d line(s) skipped\n", valid, valid ? sum / valid : 0.0, skipped);
return 0;
}
3 grades, average 12.17, 1 line(s) skipped
Common mistakes:
- Reading the grade with
%finto adouble:%fexpects the address of afloat. GCC reports the mismatch with-Wall, and without that check the value read would be wrong. - Dividing without checking
valid: with a file containing no valid grade,sum / validwould divide by zero (givingnan).
Summary
- 1fopen returns NULL on failure: always check it, and explain the error with perror.
- 2fgets reads a line without exceeding the array's size; it returns NULL at the end.
- 3sscanf returns the number of values read: compare it with the number expected.
- 4Limit the width of %s (%31s) so you never overflow an array.
- 5fclose flushes the buffer and releases the file: an open file must always be closed.
Your progress is saved on this device. Create a free account to keep your progress on all your devices.