CROSSREF Manual

C
Sample Listing
1 /*
2 * usage: wc <file1> [<file2>...]
3 *
4 * This program will count the number of lines, words, and characters in
5 * a text file and report them to standard out. When multiple files are
6 * specified a running total of all of the files is printed in addition
7 * to the individual files' totals.
8 */
9
10 #pragma runnable
11
12 #include <stdioh>
13 #include <ctypeh>
14 #include <stdlibh>
15
16 #define TRUE 1
17 #define FALSE 0
18
19 #define MAXLINE 256 /* maximum length of an input line */
20
21 long total_lines, total_words, total_chars;
22
23 void count(FILE *fp, char *file);
24
25 int main(int argc, char *argv[])
26 {
27 int i;
28 FILE *fp;
29
30 if (argc < 2)
31 {
32 fprintf(stderr, "usage: wc <file1> [<file2>...]\n");
33 return EXIT_SUCCESS;
34 }
35 for (i = 1; i < argc; i++)
36 {
37 if ((fp = fopen(argv[i], "r")) == NULL)
38 {
39 fprintf(stderr, "can't open %s\n", argv[i]);
40 continue;
41 }
42 count(fp, argv[i]);
43 if (fclose(fp) < 0)
44 fprintf(stderr, "can't close %s\n", argv[i]);
45 }
46 printf("\n*** Total: %ld line(s), %ld word(s), %ld character(s)\n",
47 total_lines,total_words,total_chars);
48 }
49
50 /*
51 * Count the number of lines, words, and characters in a text file.
52 */
53 void count(FILE *fp, char *file)
54 {
55 unsigned int nl;
56 long nw, nc;
Figure 5-1. C Sample Program (Page 1 of 2)
5-3