BETA Try the new lesson view
Code

Measurements in a file

Temperature measurements in a file: the program reads them, works out the average and writes a report to another file.

Create practice/11:

add_executable(p11_measurements measurements.c)
course_data(measurements.txt)

The second line copies measurements.txt to where ▶ runs the program (step 1).

measurements.txt – four measurements, one per line, with a dot.

measurements.c:

  • fopen(path, "r") and the check: NULL → perror and EXIT_FAILURE.
  • The loop while (count < MAX_MEASUREMENTS && fgets(...) != NULL): each line goes through strtod into the array. No checking yet.
  • The average and the report: fopen(report, "w"), two fprintf, fclose with a check.

Run it

p11_measurements and ▶:

Measurements read: 4
Average: 21.50
Report written: report.txt

report.txt has appeared in the build folder: in the Project window open build/debug (or cmake-build-debug) – the same two lines are there. Run it again: the file is overwritten, not added to ("w").

From the terminal (Alt+F12) it's the same: cd build\debug, then .\practice\11\p11_measurements.exe.

Try it

  • In measurements.c change "measurements.txt" to "measurement.txt" and run:

    measurement.txt: No such file or directory
    

    Put the name back.

  • On the last line of practice/11/measurements.txt write 22,4 instead of 22.0 and run (▶ builds first and refreshes the copy). The average should be 21.60, but the program still shows 21.50: strtod read only 22, and ,4 was quietly left over. In the next step the program will notice. Put 22.0 back.

Commit: Read and write file.