/*** This program reads the data from the a file (called tmp.dat) to a variable, x. You don't need to know the number of data points in the file a priori. The integer 'i' counts them in the while/for loop. ***/ #include <stdio.h> #include <math.h> main() { double x,sigma,x_m; int i; FILE *ifp; /* if you are reading or writing data using files you must declare some file pointers of type FILE */ ifp = fopen("tmp.dat", "r"); /* a line like this is also required*/ /* this opens the file called tmp.dat*/ /* for reading */ /* and sets the file pointer (ifp) to*/ i = 0.0; /* point at the first entry in tmp.dat*/ sigma = 0.0; x_m = 0.0; while( fscanf(ifp, "%lf", &x) == 1 ) /* the condition for this while loop. */ { /* to be true is "while fscanf returns*/ x_m += x; /* one number" ie as long as a number */ i++; /* is read, keep adding it to x_m */ } /* note that 'i' is incremented each */ x_m /= (double)i; /* time a number is read so it keeps */ printf("%d", i); /* track of the total number of numbers*/ /* for ( i=0; fscanf(ifp, "%lf", &x) ==1; i++) { x_m += x; } x_m /= (double)i; */ /* in this program we read the data from the file twice */ /* the second time we must re-set the pointer "ifp" to the */ /* beginning of the file, tmp.dat */ ifp = fopen("tmp.dat", "r"); while ( fscanf(ifp, "%lf", &x) ==1 ) { sigma += (x - x_m)*(x - x_m); } sigma = sqrt(sigma/N); printf("the mean is %lf\n the standard deviation is %lf\n", x_m, sigma); }