home *** CD-ROM | disk | FTP | other *** search
/ Piper's Pit BBS/FTP: ibm 0000 - 0009 / ibm0000-0009 / ibm0003.tar / ibm0003 / LCNOW2.ZIP / EXAMPLES / WORDCNT.C < prev    next >
Encoding:
C/C++ Source or Header  |  1988-08-04  |  1.6 KB  |  75 lines

  1. /*
  2.  * W O R D C N T
  3.  *
  4.  * Count the number of words in a file.
  5.  * WORDCNT handles only ASCII text files.
  6.  */
  7.  
  8. #include <stdio.h>
  9. #include <stdlib.h>     /* for exit() prototype */
  10.  
  11. #define MAXPATH 64
  12.  
  13. typedef enum { FALSE, TRUE } BOOLEAN;
  14.  
  15. int
  16. main(void)
  17. {
  18.     int ch;                 /* input character */
  19.     BOOLEAN wordflag;       /* control flag */
  20.     long wordcnt;           /* word counter */
  21.     FILE *fp;               /* file pointer */
  22.     char pathname[MAXPATH]; /* filename buffer */
  23.  
  24.     /*
  25.      * Prompt the user for a file name and read it.
  26.      */
  27.     printf("\nWORDCNT:\tType a filename and press ENTER.\n");
  28.     printf("Filename: ");
  29.     gets(pathname);
  30.     if (*pathname == '\0')
  31.         return (0);     /* no file named -- quit */
  32.  
  33.     /*
  34.      * Try to open the named file for reading.
  35.      * Report any failure to open the file and
  36.      * exit with an error indication.
  37.      */
  38.     fp = fopen(pathname, "r");
  39.     if (fp == NULL) {
  40.         fprintf(stderr, "Cannot open %s\n", pathname);
  41.         exit(1);
  42.     }
  43.  
  44.     /*
  45.      * Read the contents of the file and increment the
  46.      * counters for characters, words, and lines.
  47.      */
  48.     wordcnt = 0;
  49.     wordflag = FALSE;
  50.     while ((ch = fgetc(fp)) != EOF)  {
  51.         if (ch == ' ' || ch == '\t' || ch == '\n')
  52.             wordflag = FALSE;
  53.         else if (wordflag == FALSE) {
  54.             ++wordcnt;
  55.             wordflag = TRUE;
  56.         }
  57.     }
  58.     if (ferror(fp)) {
  59.         fprintf(stderr, "Error reading %s\n", pathname);
  60.         exit(2);
  61.     }
  62.  
  63.     /*
  64.      * Report the filename and the word count,
  65.      * then close the file.
  66.      */
  67.     printf("File %s: %d words\n", pathname, wordcnt);
  68.     if (fclose(fp)) {
  69.         fprintf(stderr, "Error closing %s\n", pathname);
  70.         exit(3);
  71.     }
  72.  
  73.     return (0);
  74. }
  75.