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

  1. /*
  2.  * C H A R C N T
  3.  *
  4.  * Count the number of characters in a file.  CHARCNT
  5.  * correctly 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. int
  14. main(void)
  15. {
  16.     int ch;                 /* input character */
  17.     long charcnt;           /* character charcnt */
  18.     FILE *fp;               /* file pointer */
  19.     char pathname[MAXPATH]; /* filename buffer */
  20.  
  21.     /*
  22.      * Prompt the user for a filename and read it.
  23.      */
  24.     printf("Filename: ");
  25.     scanf("%s", pathname);
  26.     putchar('\n');
  27.  
  28.     /*
  29.      * Try to open the named file for reading in text mode.
  30.      * Report any failure to open the file and exit with an
  31.      * error indication.
  32.      */
  33.     fp = fopen(pathname, "r");
  34.     if (fp == NULL) {
  35.         fprintf(stderr, "Cannot open %s\n", pathname);
  36.         exit(1);
  37.     }
  38.  
  39.     /*
  40.      * Read the contents of the file and increment the
  41.      * character count as each character is read.
  42.      */
  43.     charcnt = 0;
  44.     while ((ch = fgetc(fp)) != EOF)
  45.         ++charcnt;
  46.     if (ferror(fp) != 0) {
  47.         fprintf(stderr, "Error reading %s\n", pathname);
  48.         exit(2);
  49.     }
  50.  
  51.     /*
  52.      * Report the filename and character count
  53.      * and close the file.
  54.      */
  55.     printf("File %s contains %ld characters.\n",
  56.         pathname, charcnt);
  57.     if (fclose(fp) != 0) {
  58.         fprintf(stderr, "Error closing %s\n",
  59.             pathname);
  60.         exit(3);
  61.     }
  62.  
  63.     return (0);
  64. }
  65.