/*
Programmazione II - Esempio di codice
Example code: file read demonstration. (20000808 prelz@mi.infn.it)
*/
#include
#include
#include
/* 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 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);
}