drankinatty

Count Lines, Words & Chars (Linux wc) in C

Oct 19th, 2021 (edited)
319
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 2.07 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <ctype.h>
  3.  
  4. int main (int argc, char **argv) {
  5.  
  6.     int c, in = 0;                      /* current char, in-word flag */
  7.     size_t nc = 0, nw = 0, nl = 0;      /* count of chars, words, lines */
  8.     /* use filename provided as 1st argument (default: stdin) */
  9.     FILE *fp = argc > 1 ? fopen (argv[1], "r") : stdin;
  10.  
  11.     if (!fp) {  /* validate file open for reading */
  12.         perror ("file open failed");
  13.         return 1;
  14.     }
  15.  
  16.     if ((c = fgetc (fp)) == EOF) {      /* read 1st char, validate */
  17.         fputs ("empty-file.\n", stderr);
  18.         return 1;
  19.     }
  20.  
  21.     if (!isspace(c))                    /* if not space */
  22.         in = 1;                         /* set in-word flag */
  23.     nc++;                               /* increment char count */
  24.  
  25.     while ((c = fgetc (fp)) != EOF) {   /* read remaining chars in file */
  26.         if (isspace(c)) {               /* if whitespace */
  27.             if (in)                     /* if in-word (now 1-past end of word) */
  28.                 nw++, in = 0;           /* increment word count, clear in flag */
  29.             if (c == '\n')              /* if newline */
  30.                 nl++;                   /* increment line count */
  31.         }
  32.         else if (!in)                   /* normal character & not in-word */
  33.             in = 1;                     /* set in-word flag true */
  34.         nc++;                           /* increment char count each iteration */
  35.     }
  36.     /* non-POSIX end-of-file check */
  37.     if (in)                             /* if in at EOF (no POSIX eof) */
  38.         nw++, nl++;                     /* increment word & line count */
  39.  
  40.     /* minic Linux wc output behavior */
  41.     if (fp != stdin) {  /* not reading stdin, print filename */
  42.         printf (" %zu %zu %zu %s\n", nl, nw, nc, argv[1]);
  43.         fclose (fp);    /* close file if not stdin */
  44.     }
  45.     else    /* reading stdin, omit filename */
  46.         printf (" %zu %zu %zu\n", nl, nw, nc);
  47. }
  48.  
  49. /*
  50.  
  51. **Example Use/Output**
  52.  
  53.     $ ./bin/wc_wordcount < /var/lib/dict/words
  54.      305089 305089 3137778
  55.  
  56. */
  57.  
Add Comment
Please, Sign In to add comment