Drills: check yourself
Answer first yourself, only then open the answer.
1. What's left in the file?
grades.txt had 30 lines. The program does only this:
FILE *f = fopen("grades.txt", "w");
if (f != NULL) {
fclose(f);
}
Answer
Nothing: the file is empty. "w" erases the content as soon as it opens.
2. What does it print?
The file has two lines: first and second.
char line[20];
while (!feof(f)) {
fgets(line, sizeof line, f);
printf("> %s", line);
}
Answer
> first
> second
> second
After second, feof isn't true yet. The third fgets fails, line keeps the old line, and it is printed again. Correct: while (fgets(line, sizeof line, f) != NULL).
3. What does it print?
char *end;
double x = strtod("21,5", &end);
printf("%.1f \"%s\"\n", x, end);
Answer
21.0 ",5"
strtod stops at the comma. Since *end != '\0', the line is bad.
4. A programmer's bug or an error in the world?
For which of these does assert fit, and for which an error code?
read_measurements(NULL, t, 100, &count, &line_no)- A line
abcin the file. read_measurements(path, t, 0, &count, &line_no)- The disk is full,
fclosereturns non-zero.
Answer
1 and 3 are programmer's bugs (a broken precondition): assert. 2 and 4 are errors in the world: an error code (BAD_LINE, WRITE_FAILED).
5. What's missing?
Error write_report(const char *path, int count) {
FILE *f = fopen(path, "w");
fprintf(f, "Measurements: %d\n", count);
fclose(f);
return OK;
}
Answer
No result is checked: fopen may return NULL (→ CANNOT_OPEN), fprintf a negative number, fclose non-zero (→ WRITE_FAILED). The function always says OK, even when it wrote nothing.