#include #include #include // generate an input file to test the program... not required void generateInputFile(char *filename); void generateInputFile(char *filename) { // produce a file containing 100 random integers between 1 and 1000 FILE* outFilePtr = NULL; int c; int n; srand(time(NULL)); outFilePtr = fopen(filename, "w"); if (outFilePtr == NULL) { // something wrong fprintf(stderr, "Error: something is wrong in opening the file...\n"); return; } // write the random numbers for(c = 0 ; c < 100; c++) { n = 1 + (rand() % 1000); // a random number between 1 and 1000 if ( c == 0) { fprintf(outFilePtr, "%d", n); } else { fprintf(outFilePtr, "\n%d", n); } } fclose(outFilePtr); } int main() { FILE* inFilePtr = NULL; FILE* outFilePtr = NULL; int counter = 0; // keep track of how many numbers are read from the file so far int n; // current number from file int min; // smallest number seen so far int max; // largest number seen so far int sum = 0; // ongoing sum of all the numbers n read so far float avg = 0; // average: sum/n // Create a random file to test generateInputFile("in.dat"); // read file inFilePtr = fopen("in.dat", "r"); if (inFilePtr == NULL) { // something wrong fprintf(stderr, "Error: something is wrong in opening the file...\n"); return -1; } while(!feof(inFilePtr)) { fscanf(inFilePtr, "%d", &n); counter++; sum+=n; if (counter == 1) { min = n; max = n; } else { if (n < min) min = n; if (n > max) max = n; } } fclose(inFilePtr); // compute avg = sum / counter; // store results outFilePtr = fopen("out.dat", "w"); if (outFilePtr == NULL) { // something wrong fprintf(stderr, "Error: something is wrong in opening the file...\n"); return -1; } fprintf(outFilePtr, "%d %d %.2f", min, max, avg); fclose(outFilePtr); return 0; }