wc

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

lc.c (827B)


      1 #include <stdio.h>
      2 #include <unistd.h>
      3 
      4 int lc(FILE* fp)
      5 {
      6     int num_lines = 0;
      7     register int c;
      8     while ((c = getc(fp)) != EOF) {
      9         if (c == '\n') {
     10             num_lines++;
     11         }
     12     }
     13     // num_lines += (c != '\n');  // < judgment call, adds a line if the last line isn't followed by a newline.
     14     printf("%i\n", num_lines);
     15     return 0;
     16 }
     17 
     18 int main(int argc, char** argv)
     19 {
     20     if (argc == 1) {
     21         return lc(stdin);
     22     } else if (argc > 1) {
     23         FILE* fp = fopen(argv[1], "r");
     24         if (!fp) {
     25             perror("Could not open file");
     26             return 1;
     27         }
     28         return lc(fp) && fclose(fp);
     29     } else {
     30         printf("Usage: lc file.txt\n");
     31         printf("   or: cat file.txt | lc\n");
     32         printf("   or: lc # read from user-inputted stdin\n");
     33     }
     34     return 0;
     35 }