Sams Teach Yourself C in 21 Days

(singke) #1

TYPE& RUN 5 Counting Characters


It’s time for another Type & Run. This program, called count_ch, opens the
specified text file and counts the number of times each character occurs in it.
All the standard keyboard characters are counted, including upper- and lower-
case letters, numerals, spaces, and punctuation marks. The results are displayed
onscreen. In addition to being a potentially useful program, count_ch illustrates
some interesting programming techniques. You can use the operating system’s
redirection operator (>) to place the output in a file. For example, the command
COUNT_CH > RESULTS.TXT
runs the program and outputs the results in a file named Results.txt, instead
of displaying them onscreen. You can view the output in your text editor or
print it.

LISTINGT&R 5 count_ch.c: A program to count characters in a file
1: /* Counts the number of occurrences
2: of each character in a file. */
3: #include <stdio.h>
4: #include <stdlib.h>
5: int file_exists(char *filename);

INPUT

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

Free download pdf