/* * Version of whilesum.c that reads from file not stdin and copies * integers to output file (not useful except as illustration of * printf. * * Filenames are specified with command-line arguments. */ #include int main(int argc, char* argv[]) { if (argc < 3) { printf("usage: %s infile outfile\n", argv[0]); return 1; } 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; } }