wc

Count words in <50 lines of C
Log | Files | Refs | README

wc.c (1070B)


      1 #include <stdio.h>
      2 #include <unistd.h>
      3 
      4 int wc(FILE* fp)
      5 {
      6     register int c;
      7     int word = 0, num_words = 0;
      8     while ((c = getc(fp)) != EOF) {
      9         if (c != ' ' && c != '\n' && c != '\t') {
     10             word = 1;
     11         } else if (word) {
     12             num_words++;
     13             word = 0;
     14         }
     15     }
     16     num_words += word;
     17     printf("%i\n", num_words);
     18     return 0;
     19 }
     20 
     21 int main(int argc, char** argv)
     22 {
     23     if (argc == 1) {
     24         return wc(stdin);
     25     } else if (argc > 1) {
     26         FILE* fp = fopen(argv[1], "r");
     27         if (!fp) {
     28             perror("Could not open file");
     29             return 1;
     30         }
     31         int wc_status = wc(fp);
     32         int fclose_status = fclose(fp);
     33         return (wc_status == 0) && (fclose_status == 0);
     34         // can't do return wc_status == 0 && fclose_status == 0;
     35         // because then if wc returns with -1, fclose is not called.
     36     } else {
     37         printf("Usage: wc file.txt\n");
     38         printf("   or: cat file.txt | wc\n");
     39         printf("   or: wc # read from user-inputted stdin\n");
     40     }
     41     return 0;
     42 }