Sams Teach Yourself C in 21 Days

(singke) #1
6: int main( void )
7: {
8: char ch, source[80];
9: int index;
10: long count[127];
11: FILE *fp;
12:
13: /* Get the source and destination filenames. */
14: fprintf(stderr, “\nEnter source file name: “);
15: gets(source);
16:
17: /* See that the source file exists. */
18: if (!file_exists(source))
19: {
20: fprintf(stderr, “\n%s does not exist.\n”, source);
21: exit(1);
22: }
23: /* Open the file. */
24: if ((fp = fopen(source, “rb”)) == NULL)
25: {
26: fprintf(stderr, “\nError opening %s.\n”, source);
27: exit(1);
28: }
29: /* Zero the array elements. */
30: for (index = 31; index < 127 ; index++)
31: count[index] = 0;
32:
33: while ( 1 )
34: {
35: ch = fgetc(fp);
36: /* Done if end of file */
37: if (feof(fp))
38: break;
39: /* Count only characters between 32 and 126. */
40: if (ch > 31 && ch < 127)
41: count[ch]++;
42: }
43: /* Display the results. */
44: printf(“\nChar\t\tCount\n”);
45: for (index = 32; index < 127 ; index++)
46: printf(“[%c]\t%d\n”, index, count[index]);
47: /* Close the file and exit. */
48: fclose(fp);
49: return(0);
50: }
51: int file_exists(char *filename)
52: {
53: /* Returns TRUE if filename exists,
54: FALSE if not. */

476 Type & Run 5

LISTINGT&R 5 continued

27 448201x-T&R5 8/13/02 11:12 AM Page 476

Free download pdf