Skip to the task
Layout
Back to classic view
READTask 1 of 20 · step 1: A file and FILE *A file and FILE *
A file and FILE * in practice/09/

fopen and the NULL check, perror, the modes r/w/a, fgets and fprintf, fclose writes out the buffer, a relative path counts from the folder the program is run from.

Details & hint

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

programbuffer (RAM)disk fprintffclose Until fclose, part of the text may still be only in memory.

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 one fclose;
  • when writing, fclose returns 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.

practice 09 safe_input.c Code Diff
UNCHANGED This step does not change this file.
#include "safe_input.h"
#include <assert.h>
#include <errno.h>
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* Was the input asked to be shown (INPUT_ECHO=1)? The tests do that. */
static int echo_input(void) {
const char *e = getenv("INPUT_ECHO");
return e != NULL && strcmp(e, "1") == 0;
}
int get_line(char t[], int size) {
assert(t != NULL && size >= 2);
if (fgets(t, size, stdin) == NULL) {
return -1;
}
int echo = echo_input();
size_t n = strlen(t);
if ((n == 0 || t[n - 1] != '\n') && !feof(stdin)) {
if (echo) {
fputs(t, stdout);
}
int c;
while ((c = getchar()) != '\n' && c != EOF) {
if (echo) {
putchar(c);
}
}
if (echo) {
putchar('\n');
}
return 0;
}
t[strcspn(t, "\r\n")] = '\0';
if (echo) {
printf("%s\n", t);
}
return 1;
}
int to_int(const char *t, int *result) {
assert(t != NULL && result != NULL);
char *end;
errno = 0;
long x = strtol(t, &end, 10);
if (end == t) {
return 0;
}
while (*end == ' ') {
end++;
}
if (*end != '\0') {
return 0;
}
if (errno == ERANGE || x < INT_MIN || x > INT_MAX) {
return 0;
}
*result = (int)x;
return 1;
}