/* * 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; 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 1; } outfile = fopen(argv[2], "w"); if (outfile == NULL) { fprintf(stderr, "unable to open output file %s\n", argv[2]); return 1; } while ( (fscanf(infile, "%d", &num)) == 1 ) { fprintf(outfile, "%d\n", 2*num); } /* TODO: should check here to see that we stopped at EOF rather than because of an error */ fclose(infile); fclose(outfile); return 0; }