/* * Version of countchars.c that reads from file not stdin. * Filename is specified with command-line argument. */ #include #include /* has EXIT_SUCCESS, EXIT_FAILURE */ #include int main(int argc, char* argv[]) { if (argc < 2) { printf("usage: %s filename\n", argv[0]); return EXIT_FAILURE; } FILE * infile = fopen(argv[1], "r"); if (infile == NULL) { printf("cannot open file %s\n", argv[1]); return EXIT_FAILURE; } int count = 0; int letter_count = 0; int ch; /* input character -- NOTE that it is int not char */ /* slightly cryptic but C-idiomatic way to read to end of file */ while ((ch = fgetc(infile)) != EOF) { ++count; if (isalpha(ch)) ++letter_count; } fclose(infile); printf("%d chars, %d letters\n", count, letter_count); return EXIT_SUCCESS; }