/* * Version of loop-sum.c that reads from file not stdin. * Filename is specified with command-line argument. */ #include #include /* has EXIT_SUCCESS, EXIT_FAILURE */ int main(int argc, char* argv[]) { if (argc < 2) { printf("usage: %s filename\n", argv[0]); return EXIT_FAILURE; } FILE * infile = fopen(argv[1], "r"); if (infile == NULL) { printf("cannot open file %s\n", argv[1]); return EXIT_FAILURE; } int n; int sum = 0; /* slightly cryptic but C-idiomatic .... */ while (fscanf(infile, "%d", &n) == 1) { sum +=n; } /* check whether loop stopped because of EOF or error */ if (feof(infile)) { /* normal EOF */ fclose(infile); printf("sum %d\n", sum); return EXIT_SUCCESS; } else { /* error */ printf("invalid input\n"); fclose(infile); return EXIT_FAILURE; } }