/* * Program to count total characters in one or more files, and * also "text" characters (printable and not space). * Displays counts for each file individually and totals. * Filenames are given as command-line arguments, e.g., if the * program's name is the default a.out: * * a.out infile1 infile2 * * Somewhat silly but an example of processing one or more files, * and of using character functions. */ #include #include #include /* * count characters (all and "text") in file. * prints error message if file could not be opened. * otherwise prints counts for this file and then adds them * to global totals in *total_chars and *text_chars. */ void count_chars(char *filename, long *total_chars, long *text_chars); /* main program */ int main(int argc, char* argv[]) { long total_chars = 0; long text_chars = 0; if (argc < 2) { printf("usage: %s filename1 ....\n", argv[0]); return EXIT_FAILURE; /* portable way to return error status */ } for (int i = 1; i < argc; i++) { count_chars(argv[i], &total_chars, &text_chars); } printf("totals: %ld characters, %ld text characters\n", total_chars, text_chars); return EXIT_SUCCESS; /* portable way to return no-error status */ } void count_chars(char *filename, long *total_chars, long *text_chars) { FILE * infile = fopen(filename, "r"); if (infile == NULL) { printf("could not open file %s\n", filename); } else { /* compute counts for this file */ long total_c = 0; long text_c = 0; int inchar; while ((inchar = fgetc(infile)) != EOF) { ++total_c; if (isprint(inchar) && !isspace(inchar)) { text_c++; } } fclose(infile); printf("%s has %ld characters, %ld text characters\n", filename, total_c, text_c); /* update totals */ (*total_chars) += total_c; (*text_chars) += text_c; } }