home *** CD-ROM | disk | FTP | other *** search
- /*
- * W O R D C N T
- *
- * Count the number of words in a file.
- * WORDCNT handles only ASCII text files.
- */
-
- #include <stdio.h>
- #include <stdlib.h> /* for exit() prototype */
-
- #define MAXPATH 64
-
- typedef enum { FALSE, TRUE } BOOLEAN;
-
- int
- main(void)
- {
- int ch; /* input character */
- BOOLEAN wordflag; /* control flag */
- long wordcnt; /* word counter */
- FILE *fp; /* file pointer */
- char pathname[MAXPATH]; /* filename buffer */
-
- /*
- * Prompt the user for a file name and read it.
- */
- printf("\nWORDCNT:\tType a filename and press ENTER.\n");
- printf("Filename: ");
- gets(pathname);
- if (*pathname == '\0')
- return (0); /* no file named -- quit */
-
- /*
- * Try to open the named file for reading.
- * Report any failure to open the file and
- * exit with an error indication.
- */
- fp = fopen(pathname, "r");
- if (fp == NULL) {
- fprintf(stderr, "Cannot open %s\n", pathname);
- exit(1);
- }
-
- /*
- * Read the contents of the file and increment the
- * counters for characters, words, and lines.
- */
- wordcnt = 0;
- wordflag = FALSE;
- while ((ch = fgetc(fp)) != EOF) {
- if (ch == ' ' || ch == '\t' || ch == '\n')
- wordflag = FALSE;
- else if (wordflag == FALSE) {
- ++wordcnt;
- wordflag = TRUE;
- }
- }
- if (ferror(fp)) {
- fprintf(stderr, "Error reading %s\n", pathname);
- exit(2);
- }
-
- /*
- * Report the filename and the word count,
- * then close the file.
- */
- printf("File %s: %d words\n", pathname, wordcnt);
- if (fclose(fp)) {
- fprintf(stderr, "Error closing %s\n", pathname);
- exit(3);
- }
-
- return (0);
- }
-