Skip to the task
Layout
Back to classic view

You are looking ahead. Your place is still task 1: fopen.

READTask 13 of 20 · step 5: Common mistakesCommon mistakes
Common mistakes in practice/07/

An unchecked fopen, "w" instead of "r", a forgotten fclose, while (!feof), an unchecked end of the number, a comma, the wrong folder, an ignored error code.

Details & hint

With files, a mistake usually shows not when compiling but when running – and often silently.

Common mistakes
  • An unchecked fopen. The file isn't there, f = NULL. On Windows fgets(line, 64, f) quietly returns NULL and the program acts as if the file were empty; on Linux it crashes. After every fopen – if (f == NULL).
  • "w" instead of "r". fopen(path, "w") empties the file at once, before anything is written. Open a file you read only with "r".
  • A forgotten fclose. Part of the text stays in the buffer and, if the program crashes, never reaches the disk. For every successful fopen – an fclose, and when writing, a checked one.
  • while (!feof(f)). The last line is processed twice: feof becomes true only after a failed read. The condition is fgets(...) != NULL.
  • An unchecked end of the number. strtod("21,5", NULL) returns 21 and says nothing. Check end.
  • A comma instead of a dot. Numbers in C use a dot. A file exported from a Lithuanian spreadsheet may have 21,5: that is an error in the file, and the program must report it, not guess.
  • The wrong folder. No such file or directory although the file is there: the program was started somewhere other than where its copy is. CMakeLists.txt lacks course_data(...), or it was run from the terminal outside build/debug.
  • An ignored error code. read_measurements(...); without Error e = – the code is thrown away, and the program works with an empty array.
practice 07 daytime.c Code Diff
UNCHANGED This step does not change this file.
#include "daytime.h"
#include <assert.h>
#include <stdio.h>
#include "input.h"
int is_time(int hour, int min) {
return hour >= 0 && hour <= 23 && min >= 0 && min <= 59;
}
int to_minutes(int hour, int min) {
assert(is_time(hour, min));
return hour * 60 + min;
}
int read_time(void) {
int hour = read_int("Hour: ");
int min = read_int("Minutes: ");
while (!is_time(hour, min)) {
printf("There is no such time.\n");
hour = read_int("Hour: ");
min = read_int("Minutes: ");
}
return to_minutes(hour, min);
}
void print_time(int minutes) {
assert(minutes >= 0 && minutes < MINUTES_PER_DAY);
printf("%02d:%02d", minutes / 60, minutes % 60);
}
void print_duration(int minutes) {
assert(minutes >= 0);
printf("%d min (%d h %d min)", minutes, minutes / 60, minutes % 60);
}