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

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 04 main.c Code Diff
UNCHANGED This step does not change this file.
#include <stdio.h>
#include "input.h"
int main(void) {
int grade = read_int("Grade (0 - stop): ");
int sum = 0;
int count = 0;
while (grade != 0) {
sum += grade;
count++;
grade = read_int("Grade (0 - stop): ");
}
if (count > 0) {
printf("Average: %.2f\n", (double)sum / count);
} else {
printf("No grades.\n");
}
return 0;
}