Debian Codegraph @

texk/web2c/cwebdir/examples/wc.w

raw
1 % wc: An example of CWEB by Silvio Levy and Donald E. Knuth
2
3 \nocon % omit table of contents
4 \datethis % print date on listing
5 \def\SPARC{SPARC\-\kern.1em station}
6
7 @* An example of {\tt CWEB}. This example, based on a program by
8 Klaus Guntermann and Joachim Schrod [{\sl TUGboat\/ \bf7} (1986),
9 134--137] presents the ``word count'' program from \UNIX/, rewritten in
10 \.{CWEB} to demonstrate literate programming in \CEE/. The level of
11 detail in this document is intentionally high, for didactic purposes;
12 many of the things spelled out here don't need to be explained in
13 other programs.
14
15 The purpose of \.{wc} is to count lines, words, and/or characters in a
16 list of files. The number of lines in a file is the number of newline
17 characters it contains. The number of characters is the file length in bytes.
18 A ``word'' is a maximal sequence of consecutive characters other than
19 newline, space, or tab, containing at least one visible ASCII code.
20 (We assume that the standard ASCII code is in use.)
21
22 This version of \.{wc} has a nonstandard ``silent'' option (\.{-s}),
23 which suppresses printing except for the grand totals over all files.
24
25 @ Most \.{CWEB} programs share a common structure. It's probably a
26 good idea to state the overall structure explicitly at the outset,
27 even though the various parts could all be introduced in unnamed
28 sections of the code if we wanted to add them piecemeal.
29
30 Here, then, is an overview of the file \.{wc.c} that is defined
31 by this \.{CWEB} program \.{wc.w}:
32
33 @c
34 @<Header files to include@>@/
35 @<Global variables@>@/
36 @<Functions@>@/
37 @<The main program@>
38
39 @ We must include the standard I/O definitions, since we want to send
40 formatted output to |stdout| and |stderr|.
41
42 @<Header files...@>=
43 #include <stdio.h> /* |printf()| */
44 #include <stdlib.h> /* |exit()| */
45 #include <fcntl.h> /* |open()| */
46 #include <unistd.h> /* |close()| */
47
48 @ The |status| variable will tell the operating system if the run was
49 successful or not, and |prog_name| is used in case there's an error message to
50 be printed.
51
52 @d OK 0 /* |status| code for successful run */
53 @d usage_error 1 /* |status| code for improper syntax */
54 @d cannot_open_file 2 /* |status| code for file access error */
55
56 @<Global variables@>=
57 int status=OK; /* exit status of command, initially |OK| */
58 char *prog_name; /* who we are */
59
60 @ Now we come to the general layout of the |main| function.
61
62 @<The main...@>=
63 int main (
64 int argc, /* the number of arguments on the \UNIX/ command line */
65 char **argv) /* the arguments themselves, an array of strings */
66 {
67 @<Variables local to |main|@>@;
68 prog_name=argv[0];
69 @<Set up option selection@>;
70 @<Process all the files@>;
71 @<Print the grand totals if there were multiple files @>;
72 exit(status);
73 }
74
75 @ If the first argument begins with a `\.{-}', the user is choosing
76 the desired counts and specifying the order in which they should be
77 displayed. Each selection is given by the initial character
78 (lines, words, or characters). For example, `\.{-cl}' would cause
79 just the number of characters and the number of lines to be printed,
80 in that order. The default, if no special argument is given, is `\.{-lwc}'.
81
82 We do not process this string now; we simply remember where it is.
83 It will be used to control the formatting at output time.
84
85 If the `\.{-}' is immediately followed by `\.{s}', only summary totals
86 are printed.
87
88 @<Var...@>=
89 int file_count; /* how many files there are */
90 char *which; /* which counts to print */
91 int silent=0; /* nonzero if the silent option was selected */
92
93 @ @<Set up o...@>=
94 which="lwc"; /* if no option is given, print all three values */
95 if (argc>1 && *argv[1] == '-') {
96 argv[1]++;
97 if (*argv[1]=='s') silent=1,argv[1]++;
98 if (*argv[1]) which=argv[1];
99 argc--; argv++;
100 }
101 file_count=argc-1;
102
103 @ Now we scan the remaining arguments and try to open a file, if
104 possible. The file is processed and its statistics are given.
105 We use a |do|~\dots~|while| loop because we should read from the
106 standard input if no file name is given.
107
108 @<Process...@>=
109 argc--;
110 do {
111 @<If a file is given, try to open |*(++argv)|; |continue| if unsuccessful@>;
112 @<Initialize pointers and counters@>;
113 @<Scan file@>;
114 @<Write statistics for file@>;
115 @<Close file@>;
116 @<Update grand totals@>; /* even if there is only one file */
117 } while (--argc>0);
118
119 @ Here's the code to open the file. A special trick allows us to
120 handle input from |stdin| when no name is given.
121 Recall that the file descriptor to |stdin| is~0; that's what we
122 use as the default initial value.
123
124 @<Variabl...@>=
125 int fd=0; /* file descriptor, initialized to |stdin| */
126
127 @ @d READ_ONLY 0 /* read access code for system |open| routine */
128
129 @<If a file...@>=
130 if (file_count>0 && (fd=open(*(++argv),READ_ONLY))<0) {
131 fprintf (stderr, "%s: cannot open file %s\n", prog_name, *argv);
132 @.cannot open file@>
133 status|=cannot_open_file;
134 file_count--;
135 continue;
136 }
137
138 @ @<Close file@>=
139 close(fd);
140
141 @ We will do some homemade buffering in order to speed things up: Characters
142 will be read into the |buffer| array before we process them.
143 To do this we set up appropriate pointers and counters.
144
145 @d buf_size BUFSIZ /* \.{stdio.h}'s |BUFSIZ| is chosen for efficiency*/
146
147 @<Var...@>=
148 char buffer[buf_size]; /* we read the input into this array */
149 register char *ptr; /* the first unprocessed character in |buffer| */
150 register char *buf_end; /* the first unused position in |buffer| */
151 register int c; /* current character, or number of characters just read */
152 int in_word; /* are we within a word? */
153 long word_count, line_count, char_count; /* number of words, lines,
154 and characters found in the file so far */
155
156 @ @<Init...@>=
157 ptr=buf_end=buffer; line_count=word_count=char_count=0; in_word=0;
158
159 @ The grand totals must be initialized to zero at the beginning of the
160 program. If we made these variables local to |main|, we would have to
161 do this initialization explicitly; however, \CEE/'s globals are automatically
162 zeroed. (Or rather, ``statically zeroed.'') (Get it?)
163 @^Joke@>
164
165 @<Global var...@>=
166 long tot_word_count, tot_line_count, tot_char_count;
167 /* total number of words, lines, and chars */
168
169 @ The present section, which does the counting that is \.{wc}'s {\it raison
170 d'\^etre}, was actually one of the simplest to write. We look at each
171 character and change state if it begins or ends a word.
172
173 @<Scan...@>=
174 while (1) {
175 @<Fill |buffer| if it is empty; |break| at end of file@>;
176 c=*ptr++;
177 if (c>' ' && c<0177) { /* visible ASCII codes */
178 if (!in_word) {word_count++; in_word=1;}
179 continue;
180 }
181 if (c=='\n') line_count++;
182 else if (c!=' ' && c!='\t') continue;
183 in_word=0; /* |c| is newline, space, or tab */
184 }
185
186 @ Buffered I/O allows us to count the number of characters almost for free.
187
188 @<Fill |buff...@>=
189 if (ptr>=buf_end) {
190 ptr=buffer; c=read(fd,ptr,buf_size);
191 if (c<=0) break;
192 char_count+=c; buf_end=buffer+c;
193 }
194
195 @ It's convenient to output the statistics by defining a new function
196 |wc_print|; then the same function can be used for the totals.
197 Additionally we must decide here if we know the name of the file
198 we have processed or if it was just |stdin|.
199
200 @<Write...@>=
201 if (!silent) {
202 wc_print(which, char_count, word_count, line_count);
203 if (file_count) printf (" %s\n", *argv); /* not |stdin| */
204 else printf ("\n"); /* |stdin| */
205 }
206
207 @ @<Upda...@>=
208 tot_line_count+=line_count;
209 tot_word_count+=word_count;
210 tot_char_count+=char_count;
211
212 @ We might as well improve a bit on \UNIX/'s \.{wc} by displaying the
213 number of files too.
214
215 @<Print the...@>=
216 if (file_count>1 || silent) {
217 wc_print(which, tot_char_count, tot_word_count, tot_line_count);
218 if (!file_count) printf("\n");
219 else printf(" total in %d file%s\n",file_count,file_count>1?"s":"");
220 }
221
222 @ Here now is the function that prints the values according to the
223 specified options. The calling routine is supposed to supply a
224 newline. If an invalid option character is found we inform
225 the user about proper usage of the command. Counts are printed in
226 8-digit fields so that they will line up in columns.
227
228 @d print_count(n) printf("%8ld",n)
229
230 @<Fun...@>=
231 void wc_print(
232 char *which, /* which counts to print */
233 long char_count, long word_count, long line_count) /* given totals */
234 {
235 while (*which)
236 switch (*which++) {
237 case 'l': print_count(line_count); break;
238 case 'w': print_count(word_count); break;
239 case 'c': print_count(char_count); break;
240 default: if ((status & usage_error)==0) {
241 fprintf (stderr, "\nUsage: %s [-lwc] [filename ...]\n", prog_name);
242 @.Usage: ...@>
243 status|=usage_error;
244 }
245 }
246 }
247
248 @ Incidentally, a test of this program against the system \.{wc}
249 command on a \SPARC\ showed that the ``official'' \.{wc} was slightly
250 slower. Furthermore, although that \.{wc} gave an appropriate error
251 message for the options `\.{-abc}', it made no complaints about the
252 options `\.{-labc}'! Dare we suggest that the system routine might have been
253 better if its programmer had used a more literate approach?
254
255 @* Index.
256 Here is a list of the identifiers used, and where they appear. Underlined
257 entries indicate the place of definition. Error messages are also shown.