Sams Teach Yourself C in 21 Days

(singke) #1
Counting Characters 477

55: FILE *fp;
56: if ((fp = fopen(filename, “r”)) == NULL)
57: return 0;
58: else
59: {
60: fclose(fp);
61: return 1;
62: }
63: }

Look first at the function file_exists()on lines 51 to 63. Passed a filename as
its argument, this function returns TRUEif the file exists and FALSEif it doesn’t.
Code in the function checks for the file by trying to open it in read mode (line 56). This
is a general-purpose function that you can use in other programs.
Next, note how screen messages are displayed with the fprintf()function rather than
printf(), as in line 14, for example. Why is this? Because printf()always sends out-
put to stdout, the user won’t see any messages if the redirection operator is used to
direct program output to a disk file. Using fprintf()forces the messages to stderr,
which is always the screen.
Finally, observe how the numerical value of each character is used as an index to the
results array (lines 40 and 41). For example, the numerical value 32 represents a space,
so the array element count[32]is used to keep a total of spaces.
When you run this program, you will be prompted to enter a file name:
Enter source file name: count_ch.c
After entering the file name, a count of the characters will be displayed. The following is
the output from entering the count_ch.c listing:
Char Count
[ ] 434
[!] 1
[“] 14
[#] 2
[$] 0
[%] 4
[&] 2
[‘] 0
[(] 29
[)] 29
[*] 24
[+] 6
[,] 11

LISTINGT&R 5 continued

ANALYSIS

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

Free download pdf