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/10/

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 10 cities.c Code Diff
UNCHANGED This step does not change this file.
#include <assert.h>
#include <stdio.h>
#include <string.h>
#define MAX_NAME 20
#define CITY_COUNT 5
/* City: three pieces of data of different types under one name. */
typedef struct {
char name[MAX_NAME];
int population;
double area; /* km2 */
} City;
/* Prints one city. Before: c != NULL. */
void print_city(const City *c) {
assert(c != NULL);
printf("%s: %d people, %.1f km2\n", c->name, c->population, c->area);
}
/* Gets a COPY of the city: the original doesn't change. */
void grow_copy(City c, int count) {
c.population += count;
}
/* Gets a pointer to the city: changes the original. Before: c != NULL. */
void grow(City *c, int count) {
assert(c != NULL);
c->population += count;
}
/* Population density, people per km2. Before: c != NULL, c->area > 0. */
double density(const City *c) {
assert(c != NULL && c->area > 0);
return c->population / c->area;
}
/* The index of the city with this name, or -1.
Before: n >= 0, t and name not NULL. */
int find_city(const City t[], int n, const char *name) {
assert(n >= 0 && t != NULL && name != NULL);
for (int i = 0; i < n; i++) {
if (strcmp(t[i].name, name) == 0) {
return i;
}
}
return -1;
}
/* Sorts by population, largest first, by selection.
Before: n >= 0, t != NULL. */
void sort_by_population(City t[], int n) {
assert(n >= 0 && t != NULL);
for (int i = 0; i < n - 1; i++) {
int max = i;
for (int j = i + 1; j < n; j++) {
if (t[j].population > t[max].population) {
max = j;
}
}
City temp = t[i];
t[i] = t[max];
t[max] = temp;
}
}
int main(void) {
City kaunas = {"Kaunas", 300000, 157.0};
City vilnius = {.name = "Vilnius", .population = 600000, .area = 401.0};
print_city(&kaunas);
print_city(&vilnius);
printf("sizeof(City): %zu\n", sizeof(City));
City copy = kaunas;
copy.population = 0;
printf("kaunas: %d, copy: %d\n", kaunas.population, copy.population);
grow_copy(kaunas, 1000);
printf("After grow_copy: %d\n", kaunas.population);
grow(&kaunas, 1000);
printf("After grow: %d\n", kaunas.population);
City cities[CITY_COUNT] = {
{"Klaipeda", 150000, 98.0}, {"Panevezys", 85000, 50.0}, {"Vilnius", 600000, 401.0},
{"Alytus", 50000, 40.0}, {"Kaunas", 300000, 157.0},
};
sort_by_population(cities, CITY_COUNT);
printf("\nBy population:\n");
for (int i = 0; i < CITY_COUNT; i++) {
printf("%d. ", i + 1);
print_city(&cities[i]);
}
int k = find_city(cities, CITY_COUNT, "Alytus");
if (k != -1) {
printf("Alytus is in place %d, density %.0f people/km2\n", k + 1, density(&cities[k]));
}
if (find_city(cities, CITY_COUNT, "Utena") == -1) {
printf("Utena is not on the list.\n");
}
return 0;
}