/** * Program to sum integers read from file. */ #include #include int main(int argc, char* argv[]) { int input; int sum = 0; FILE* infile; if (argc < 2) { fprintf(stderr, "need parameter: input filename\n"); return EXIT_FAILURE; } infile = fopen(argv[1], "r"); if (infile == NULL) { fprintf(stderr, "cannot open input file %s\n", argv[1]); return EXIT_FAILURE; } while(fscanf(infile, "%d", &input) == 1) { sum += input; } /* if fscanf did not return 1 for any reason other than EOF, error */ if (!feof(infile)) { fprintf(stderr, "invalid input value\n"); fclose(infile); return EXIT_FAILURE; } fclose(infile); printf("sum is %d\n", sum); return EXIT_SUCCESS; }