#include #include int wc(FILE* fp) { register int c; int word = 0, num_words = 0; while ((c = getc(fp)) != EOF) { if (c != ' ' && c != '\n' && c != '\t') { word = 1; } else if (word) { num_words++; word = 0; } } num_words += word; printf("%i\n", num_words); return 0; } int main(int argc, char** argv) { if (argc == 1) { return wc(stdin); } else if (argc > 1) { FILE* fp = fopen(argv[1], "r"); if (!fp) { perror("Could not open file"); return 1; } int wc_status = wc(fp); int fclose_status = fclose(fp); return (wc_status == 0) && (fclose_status == 0); // can't do return wc_status == 0 && fclose_status == 0; // because then if wc returns with -1, fclose is not called. } else { printf("Usage: wc file.txt\n"); printf(" or: cat file.txt | wc\n"); printf(" or: wc # read from user-inputted stdin\n"); } return 0; }