/* * FILEIO -- count the number of characters, words, and lines in a file * * Usage: fileio * * Inputs (from standard input) * -- file name * Outputs * -- for each file (ht is a horizontal tab): * ht ht ht * -- and at the end, print the totals: * ht ht ht cumulative * * Exit Code: number of files it couldn't open * * written for ECS 030, Fall 2015 * * Matt Bishop, Oct. 1, 2015 * (adapted from an earlier program) * */ #include #include #include /* * MACROS */ #define MAXFILENAMESIZE 1024 /* max length of file name */ /* these are values for the state variable */ #define IN_WORD 1 /* currently inside a word */ #define NOTIN_WORD 0 /* currently not in a word */ /* * globals * * these keep the cumulative counts */ int totnl = 0; /* total line count */ int totnw = 0; /* total word count */ int totnc = 0; /* total char count */ /* * WC -- count the number of lines, words, and chars in the input * * assumptions: * a word is a maximal sequence of nonspace characters, so * the quote "+++ --- hi bye 879+3" has 5 words ("+++", "---", * "hi", "bye", and "879+3") * * parameters: char *filename the file name * FILE *fp the file pointer * returns: nothing * exceptions: none */ void wc(char *filename, FILE *fp) { int c; /* input char */ int nl, nw, nc; /* line, word, char count */ int state; /* state: in or not in a word? */ /* * initialize */ nl = nw = nc = 0; /* nothing yet */ state = NOTIN_WORD; /* start not in a 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); } /* * it all begins here */ int main(void) { char fname[MAXFILENAMESIZE]; /* the current file */ FILE *fp; /* file pointer */ int rv = 0; /* return value */ /* * read one file name per line, and do the dirty deeds * then get the next one, -, until EOF */ while(printf("file name> "), fgets(fname, MAXFILENAMESIZE, stdin) != NULL){ /* clobber the trailing newline */ if (fname[strlen(fname)-1] == '\n') fname[strlen(fname)-1] ='\0'; /* open the file */ if ((fp = fopen(fname, "r")) == NULL){ /* oops ... one more error */ fprintf(stderr, "Could not open file %s\n", fname); rv++; continue; } /* count the characters, etc. */ wc(fname, fp); /* now close it */ (void) fclose(fp); } /* * print the cumulative counts */ totnl += nl; totnw += nw; totnc += nc; printf("\n%6d\t%6d\t%6d\tcumulative\n", totnl, totnw, totnc); /* * say goodbye! */ return(rv); }