/* * Simple contrived example of formatted I/O on files: * Read integers from input, sum, write partial sums to output file. * Filenames given as command-line arguments. */ #include int main(int argc, char *argv[]) { if (argc != 3) { printf("arguments: infile outfile\n"); return 1; } FILE * infile = fopen(argv[1], "r"); if (infile == NULL) { printf("cannot open input\n"); return 1; } FILE * outfile = fopen(argv[2], "w"); if (outfile == NULL) { printf("cannot open output\n"); return 1; } int n; int sum = 0; while (fscanf(infile, "%d", &n) == 1) { sum += n; fprintf(outfile, "%d\n", sum); } /* loop ends either on EOF or on bad input */ if (!feof(infile)) { /* if not EOF, must be bad input */ printf("error in input\n"); fclose(infile); fclose(outfile); return 1; } printf("%d\n", sum); fclose(infile); fclose(outfile); return 0; }