/* * Simple example of getting input from a file -- read integers from * file and compute sum. * Uses command-line argument to specify filename. * File should contain integers, in the same format as what would be * entered interactively. */ #include int main(int argc, char* argv[]) { /* * check that user supplied two arguments * by convention argv[0] is something that identifies the * program (often its filename -- e.g., a.out). */ if (argc != 2) { printf("usage %s infile\n", argv[0]); return 1; } /* * open input file -- note that fopen returns NULL if it * could not do this, e.g., file not found */ FILE * infile = fopen(argv[1], "r"); if (infile == NULL) { printf("could not open input file %s\n", argv[1]); return 1; } /* * read integers from input file and sum * uses scanf and stops when either it gets to the end of the file * or it encounters something that is not an integer. */ int sum = 0; int n; while (fscanf(infile, "%d", &n) == 1) { sum += n; } /* * distinguish between two reasons for ending loop -- end of file * encountered, or invalid input (not integers). */ if (feof(infile)) { /* loop stopped because everything in the file was read */ printf("sum is %d\n", sum); fclose(infile); return 0; } else { /* loop stopped because of not-integer data in file */ /* * FIXME? not a very helpful message, so could keep a count * of lines read in the file and print it here? */ printf("invalid input\n"); fclose(infile); return 1; } }