A file and FILE *
So far the gradebook forgets everything when the program ends. For the data to stay, it has to be written to a file and read back next time.
FILE * and fopen
#include <stdio.h>
FILE *f = fopen("measurements.txt", "r");
if (f == NULL) {
perror("measurements.txt");
return EXIT_FAILURE;
}
fopen returns a pointer to a FILE – a handle through which the program works with the file. If it can't open it (no such file, no permission), it returns NULL. Always check: on Windows fgets with NULL quietly reads nothing, and on Linux (and GitHub CI) the program crashes.
perror prints your text and the reason, e.g.:
measurements.txt: No such file or directory
The second argument of fopen is the mode:
| mode | what it does | if the file doesn't exist |
|---|---|---|
"r" |
read | NULL |
"w" |
write from scratch: erases the old content | creates it |
"a" |
write at the end | creates it |
Reading and writing
The keyboard is a FILE * too: stdin. So a file is read with the same fgets as input:
char line[64];
while (fgets(line, sizeof line, f) != NULL) {
/* one line, with '\n' at the end */
}
fgets returns NULL when the file has ended (or an error happened). Writing uses fprintf – the same printf, just with a file in front:
fprintf(out, "Average: %.2f\n", average);
fclose
fprintf writes into a buffer in memory, and it reaches the disk later. fclose(f) writes out what's left and closes the file. So:
- for every successful
fopen– exactly onefclose; - when writing,
fclosereturns an error (not 0) if the last part couldn't be written (e.g. the disk is full). It's the last place to see that error – check it.
The path: where the program is run from
"measurements.txt" is a relative path. It is counted from the folder the program is run from (the working folder), not from where the .c or .exe file is.
CLion's ▶ and Debug start the program in the build folder – build/debug (or cmake-build-debug). That's why the course's CMake has a helper, course_data: on Build it copies the program's data files to where the program will run. Nothing needs setting in CLion:
add_executable(p11_measurements measurements.c)
course_data(measurements.txt)
Edit the original practice/11/measurements.txt – the next Build refreshes the copy. What the program writes (e.g. report.txt) appears in the same build folder.