/* Counts the number of occurrences of each character in a file. */ #include #include int file_exists(char *filename); main() { char ch, source[80]; int index; long count[127]; FILE *fp; /* Get the source and destination filenemes. */ fprintf(stderr, "\nEnter source file name: "); gets(source); /* See that the source file exists. */ if (!file_exists(source)) { fprintf(stderr, "\n%s does not exist.\n", source); exit(1); } /* Open the file. */ if ((fp = fopen(source, "rb")) == NULL) { fprintf(stderr, "\nError opening %s.\n", source); exit(1); } /* Zero the array elements. */ for (index = 31; index < 127 ; index++) count[index] = 0; while ( 1 ) { ch = fgetc(fp); /* Done if end of file */ if (feof(fp)) break; /* Count only characterss between 32 and 126. */ if (ch > 31 && ch < 127) count[ch]++; } /* Display the results. */ printf("\nChar\t\tCount\n"); for (index = 32; index < 27 ; index++) printf("[%c]\t%d\n", index, count[index]); /* Close the file and exit. */ fclose(fp); return(0); } int file_exists(char *filename) { /* Return TRUE if filename exists, FALSE if not. */ FILE *fp; if ((fp = fopen(filename, "r")) == NULL) return 0; else { fclose(fp); return 1; } }