/* * Version of whilesum.c that reads from file not stdin and writes * partial sums to output file (mostly useful as an illustration of * fprintf). * * Filenames are specified with command-line arguments. */ #include #include int main(int argc, char* argv[]) { if (argc < 3) { printf("usage: %s infile outfile\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; } FILE * outfile = fopen(argv[2], "w"); if (outfile == NULL) { printf("cannot open file %s\n", argv[2]); return EXIT_FAILURE; } int n; int sum = 0; /* slightly cryptic but C-idiomatic .... */ while (fscanf(infile, "%d", &n) == 1) { fprintf(outfile, "partial sum %d\n", sum); sum +=n; } /* check whether loop stopped because of EOF or error */ if (feof(infile)) { /* normal EOF */ fclose(infile); fprintf(outfile, "sum %d\n", sum); printf("sum %d\n", sum); return EXIT_SUCCESS; } else { /* error */ puts("invalid input"); fclose(infile); return EXIT_FAILURE; } }