/* * Program to read integers from a file, double them, and write the * results to a file. Names of files are supplied as command-line * arguments. (Yes, it's silly, but it's an example of using fscanf * and fprintf.) */ #include #include int main(int argc, char *argv[]) { int num; int exit_status; FILE *infile; FILE *outfile; if (argc < 3) { fprintf(stderr, "usage: %s infile outfile\n", argv[0]); return 1; } infile = fopen(argv[1], "r"); if (infile == NULL) { fprintf(stderr, "unable to open input file %s\n", argv[1]); return EXIT_FAILURE; } outfile = fopen(argv[2], "w"); if (outfile == NULL) { fprintf(stderr, "unable to open output file %s\n", argv[2]); return EXIT_FAILURE; } while (fscanf(infile, "%d", &num) == 1) { fprintf(outfile, "%d\n", num * 2); } if (feof(infile)) { exit_status = EXIT_SUCCESS; } else { fprintf(stderr, "input error\n"); exit_status = EXIT_FAILURE; } fclose(infile); fclose(outfile); return exit_status; }