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→perrorandEXIT_FAILURE.- The loop
while (count < MAX_MEASUREMENTS && fgets(...) != NULL): each line goes throughstrtodinto the array. No checking yet. - The average and the report:
fopen(report, "w"), twofprintf,fclosewith 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.cchange"measurements.txt"to"measurement.txt"and run:measurement.txt: No such file or directoryPut the name back.
-
On the last line of
practice/11/measurements.txtwrite22,4instead of22.0and run (▶ builds first and refreshes the copy). The average should be 21.60, but the program still shows21.50:strtodread only22, and,4was quietly left over. In the next step the program will notice. Put22.0back.
Commit: Read and write file.