/* * Program to add numbers. * * Input and output from files, names given by command-line arguments. */ #include #include #include int main(int argc, char *argv[]) { int input; int sum = 0; FILE *infile; FILE *outfile; if (argc < 3) { fprintf(stderr, "usage: %s infile outfile\n", argv[0]); return EXIT_FAILURE; } if (strcmp(argv[1], argv[2]) == 0) { fprintf(stderr, "error: input and output file are the same\n"); return EXIT_FAILURE; } infile = fopen(argv[1], "rb"); if (infile == NULL) { fprintf(stderr, "unable to open input file %s\n", argv[1]); return EXIT_FAILURE; } outfile = fopen(argv[2], "wb"); if (outfile == NULL) { fprintf(stderr, "unable to open output file %s\n", argv[2]); return EXIT_FAILURE; } while (fscanf(infile, "%d", &input) == 1) { sum += input; } fprintf(outfile, "result is %d\n", sum); fclose(infile); fclose(outfile); return EXIT_SUCCESS; }