/* Program LOGGER_1.C ** ** Illustrates logging to a file by appending to an existing text file. ** ** Program checks to see if file "log.dat" exists and if so, closes it. ** Otherwise, the file is created. Note that if the Flashlite should ** accidentally reboot, the prior file is not overwritten. ** ** "Samples" are periodically appended to the file. Note that the log ** file is opened for a very brief time to avoid losing the entire file ** if power should be lost. ** ** As an additonal safeguard, the log file is copied to a .bk1 file after ** each 25 samples. To safeguard against the loss of power during this ** copy, the .bk1 file is first copied to a .bk2 file and then the current ** file is copied to the .bk1 file. ** ** Note that the meas_temp routine is a stub intended to simulate the ** making of a temperature measurement. ** ** Important points which are illustrated include; ** ** Ascertaining whether a file currently exists. ** Appending to a file. ** Use of the system() command, in this case, to copy a file. ** Note the use of an unsigned int for variable n, as the value ** exceeds 32767. ** Use of a static in a function. ** ** Note that if power is lost and the system reboots, n will again start ** at zero and thus the log file might contain .. 48, 49, 0. Although, ** this is a solvable problem, I didn't do so as this may be useful in ** interpretting the data as it indicates there was an interruption. ** ** copyright, Peter H. Anderson, Baltimore, MD, Sept, '00 */ #include <stdio.h> #include <stdlib.h> #include <dos.h> float meas_temp(void); void main(void) { FILE *f1; unsigned int n; float temperature; f1 = fopen("log.dat", "rt"); /* check to see if the file exists */ if (f1 == NULL) { f1 = fopen("log.dat", "wt"); /* if not, create one */ fclose(f1); } else { fclose(f1); } for (n=0; n <50000; n++) { temperature = meas_temp(); if ( ((n%25) == 0) && (n!=0) ) /* every 25 samples, make a backup */ { system("copy log.bk1 log.bk2"); /* copy the backup to a second backup */ system("copy log.dat log.bk1"); /* and the current file to the first backup */ } f1 = fopen("log.dat", "a+t"); /* open file for appending */ fprintf(f1, "%d, %.2f\n", n, temperature); fclose(f1); /* and immediately close it */ printf("%d, %.2f\n", n, temperature); sleep(5); } } float meas_temp(void) { /* this is a stub that returns a temperature in the range ** of 23.0 to 34.0. */ static int n=0; float T; T = 23.0 + n; ++n; n=n%10; /* n is in range of 0 - 9 */ return(T); }