BETA Try the new lesson view
Code

Error codes in the program

Now the program checks every line and reports every error in words. Reading and writing move into functions, so the start and end of main are rearranged – a deliberate restructuring, not a new program: the calculation and the output stay the same.

bad.txt – three lines, 21,5 on the second.

CMakeLists.txt – course_data(measurements.txt bad.txt): the new file goes to where the program runs too.

measurements.c:

  • typedef enum { OK = 0, ... } Error; and error_text(e) – a readable text for each code.
  • print_error(path, e, line_no) – one place that prints an error; for a bad line it adds the line number.
  • Error read_measurements(path, t, max, &count, &line_no) – the same fgets loop, but with strtod's end checked and the lines counted. Couldn't open – CANNOT_OPEN; no perror any more.
  • Error write_report(path, count, average) – checks both fprintf and fclose.
  • At the end of main, two more files: bad.txt and missing.txt, which doesn't exist.

Run it

p11_measurements and ▶:

Measurements read: 4
Average: 21.50
Report written: report.txt
bad.txt, line 2: not a number
missing.txt: cannot open the file

Every error comes with its file, and a bad line with its number.

The code in the debugger

A breakpoint at if (end == line || *end != '\0') {, Debug. The first four stops are measurements.txt: end = "", because the while has already skipped the '\n'. The fifth stop is the first line of bad.txt, the sixth the second: line = "21,5\n", x = 21, end = ",5\n". F8 – and the program goes to BAD_LINE.

Commit: Return error codes.