/* Programmazione II - Esempio di codice Example code: file read demonstration. (20000808 prelz@mi.infn.it) */ #include <stdio.h> #include <stdlib.h> #include <math.h> /* This include file contains structure definitions and #defines. */ #include "ex1.h" int main(int argc, char *argv[]) { char in[800]; /* Generic input storage */ FILE *in_file; int record_count = 0; int n_read_records; measurement *read_records; double old_average, average=0, nvariance=0, variance; int i; printf("Please enter the name of the input file ---> "); fgets(in, sizeof(in), stdin); in[strlen(in)-1] = '\000'; /* Remove trailing newline */ in_file = fopen(in,"r"); if (in_file == NULL) { fprintf(stderr, "Cannot read from file %s. ", in); perror(""); /* Prints the current error status */ exit(1); } /* The input file begins with the number of records. */ if (fread(&record_count, sizeof(int), 1, in_file) < 1) { fprintf(stderr, "Error reading from input file. "); perror(""); fclose(in_file); exit(1); } printf ("\n********* The file contains %d records.\n\n",record_count); /* Allocate storage for all of the data */ read_records = (measurement *)malloc(record_count * sizeof(measurement)); if (read_records == NULL) { fprintf(stderr,"Not enough memory to store %d records.\n", record_count); } n_read_records = fread(read_records, sizeof(measurement), record_count, in_file); if (n_read_records < record_count) { fprintf(stderr,"Warning: could read only %d records.\n",n_read_records); perror(""); } /* We can safely close the file now */ fclose(in_file); /* Let's try to print the records we just read */ for (i=0;i<n_read_records;i++) { printf ("\n********* Reading record # %d.\n\n",i+1); printf ("Observer name: %s\n", read_records[i].observer_name); printf ("Date and time : %02d-%02d-%04d %02d:%02d\n", read_records[i].dt.day, read_records[i].dt.month, read_records[i].dt.year, read_records[i].dt.hours, read_records[i].dt.minutes); printf ("Temperature: %7.5g C\n", read_records[i].temperature); printf ("Meas. value: %15.13g\n", read_records[i].value); printf ("Comments: %s\n", read_records[i].comments); /* Compute average and std. deviation values */ old_average = average; average = (double)i/(double)(i+1)*average + (double)1/(double)(i+1)*read_records[i].value; nvariance = (double)1/(double)(i+1) * ( (double)(i) * nvariance + pow(read_records[i].value,2) + (double)i * pow(old_average,2) - (double)(i+1) * pow(average,2) ); if (i > 0) variance = (double)(i+1)*nvariance/(double)i; else variance = nvariance; printf ("Current average: %15.13g\n",average); printf ("Current std dev: %15.13g\n",sqrt(variance)); } printf("\n"); /* It's always better to remember to free areas... */ free(read_records); exit(0); }