#include #define MAXFILENAMESIZE 1024 /* max length of a file name */ #define IN_WORD 1 /* currently inside a word */ #define NOTIN_WORD 0 /* currently not in a word */ /* * count the number of lines, words, and chars in the input * a word is a maximal sequence of nonspace characters, so * the quote "+++ --- hi bye 879+3" has 5 words ("+++", "---", * "hi", "bye", and "879+3") */ void wc(char *filename, FILE *fp) { register int c; /* input char */ static int totnl = 0; /* total line count */ static int totnw = 0; /* total word count */ static int totnc = 0; /* total char count */ register int nl; /* line count */ register int nw; /* word count */ register int nc; /* char count */ register int state; /* in or not in a word? */ /* * initialize */ nl = nw = nc = 0; state = NOTIN_WORD; /* * handle input a char at a time */ while((c = getc(fp)) != EOF){ /* got another character */ nc++; /* is it a newline? */ if (c == '\n') nl++; /* is it a word separator? */ if (c == ' ' || c == '\t' || c == '\n') /* YES -- change state */ state = NOTIN_WORD; else if (state == NOTIN_WORD){ /* NO -- we're now in a word; update */ /* the counter and state if need be */ state = IN_WORD; nw++; } } /* * increment the cumulative counts */ totnl += nl; totnw += nw; totnc += nc; /* * announce the results and quit */ printf("%6d\t%6d\t%6d\t%s\n", nl, nw, nc, filename); printf("%6d\t%6d\t%6d\tcumulative\n", totnl, totnw, totnc); } /* * read a file name from the standard input, * open it, and count characters, words, and lines */ void main(void) { char fname[MAXFILENAMESIZE]; /* the file name(s) */ FILE *fp; /* file pointer */ while(printf("file name> "), gets(fname) != NULL){ /* open the file */ if ((fp = fopen(fname, "r")) == NULL){ fprintf(stderr, "Cound not open file %s\n", fname); continue; } /* count the characters, etc. */ wc(fname, fp); /* now close it */ (void) fclose(fp); } /* * say goodbye! */ exit(0); }