#include #include int wc(FILE* fp) { char c[1]; int seen_word = 0, seen_sep_after_word = 0, num_words = 0; int fn = fileno(fp); while (read(fn, c, sizeof(c)) > 0) { if (*c == '\n' || *c == ' ' || *c == '\t') { if (seen_word) { seen_sep_after_word = 1; } } else { seen_word = 1; } // exercise: what happens if you only track seen_sep, // instead of seen_sep_after_word? // test with: $ echo " hello world" | ./wc if (seen_word && seen_sep_after_word) { num_words++; seen_sep_after_word = seen_word = 0; } } num_words+=seen_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; } return wc(fp) && fclose(fp); } else { printf("Usage: ww file.txt\n"); printf(" or: cat file.txt | ww\n"); printf(" or: ww # read from user-inputted stdin\n"); } return 0; }