home *** CD-ROM | disk | FTP | other *** search
- /*
- * C H A R C N T
- *
- * Count the number of characters in a file. CHARCNT
- * correctly handles only ASCII text files.
- */
-
- #include <stdio.h>
- #include <stdlib.h> /* for exit() prototype */
-
- #define MAXPATH 64
-
- int
- main(void)
- {
- int ch; /* input character */
- long charcnt; /* character charcnt */
- FILE *fp; /* file pointer */
- char pathname[MAXPATH]; /* filename buffer */
-
- /*
- * Prompt the user for a filename and read it.
- */
- printf("Filename: ");
- scanf("%s", pathname);
- putchar('\n');
-
- /*
- * Try to open the named file for reading in text mode.
- * 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
- * character count as each character is read.
- */
- charcnt = 0;
- while ((ch = fgetc(fp)) != EOF)
- ++charcnt;
- if (ferror(fp) != 0) {
- fprintf(stderr, "Error reading %s\n", pathname);
- exit(2);
- }
-
- /*
- * Report the filename and character count
- * and close the file.
- */
- printf("File %s contains %ld characters.\n",
- pathname, charcnt);
- if (fclose(fp) != 0) {
- fprintf(stderr, "Error closing %s\n",
- pathname);
- exit(3);
- }
-
- return (0);
- }
-