Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <ctype.h>
- int main (int argc, char **argv) {
- int c, in = 0; /* current char, in-word flag */
- size_t nc = 0, nw = 0, nl = 0; /* count of chars, words, lines */
- /* use filename provided as 1st argument (default: stdin) */
- FILE *fp = argc > 1 ? fopen (argv[1], "r") : stdin;
- if (!fp) { /* validate file open for reading */
- perror ("file open failed");
- return 1;
- }
- if ((c = fgetc (fp)) == EOF) { /* read 1st char, validate */
- fputs ("empty-file.\n", stderr);
- return 1;
- }
- if (!isspace(c)) /* if not space */
- in = 1; /* set in-word flag */
- nc++; /* increment char count */
- while ((c = fgetc (fp)) != EOF) { /* read remaining chars in file */
- if (isspace(c)) { /* if whitespace */
- if (in) /* if in-word (now 1-past end of word) */
- nw++, in = 0; /* increment word count, clear in flag */
- if (c == '\n') /* if newline */
- nl++; /* increment line count */
- }
- else if (!in) /* normal character & not in-word */
- in = 1; /* set in-word flag true */
- nc++; /* increment char count each iteration */
- }
- /* non-POSIX end-of-file check */
- if (in) /* if in at EOF (no POSIX eof) */
- nw++, nl++; /* increment word & line count */
- /* minic Linux wc output behavior */
- if (fp != stdin) { /* not reading stdin, print filename */
- printf (" %zu %zu %zu %s\n", nl, nw, nc, argv[1]);
- fclose (fp); /* close file if not stdin */
- }
- else /* reading stdin, omit filename */
- printf (" %zu %zu %zu\n", nl, nw, nc);
- }
- /*
- **Example Use/Output**
- $ ./bin/wc_wordcount < /var/lib/dict/words
- 305089 305089 3137778
- */
Add Comment
Please, Sign In to add comment