Debian Codegraph @

texmf-dist/doc/latex/cweb-latex/examples/wcltx.w

raw
1 % $Id: wcltx.w,v 1.4 1995/08/29 17:27:57 schrod Exp $
2 %------------------------------------------------------------
3
4 %
5 % wc: An example of CWEB by Silvio Levy and Donald E. Knuth
6 %
7 % [LaTeX]
8 % (history at end)
9
10
11 %% -js:
12 %% should rework it: ANSI C compliance, POSIX.2 compliant option
13 %% parsing with getopt(), including *all* required header files (ie,
14 %% POSIX.1 compliance), using POSIX return codes and types, etc.
15
16
17
18 \documentclass{cweb}
19
20 \usepackage{rcs}
21
22
23 %
24 % some tags for this document
25 %
26 \def\CEE/{C\spacefactor 1000 }
27 \def\cweb{{\tt CWEB\/}}
28 \def\SPARC{SPARC\-\kern.1em station}
29 \def\UNIX/{{\small UNIX\/}}
30 \def\wc{{\tt wc\/}}
31 \def\WEB{{\tt WEB\/}}
32
33 \hfuzz=0.5pt
34
35
36
37
38 \begin{document}
39
40
41
42 \title{Counting words}
43 \author{Silvio Levy\and Donald E. Knuth}
44 \begingroup
45 \def\thefootnote{\hbox{$^*$}}
46 \footnotetext[0]{\LaTeX{} markup by Joachim Schrod.}
47 \endgroup
48 \RCSdate $Date: 1995/08/29 17:27:57 $
49
50 \maketitle
51
52 % not very interesting, only one starred section
53 % \tableofcontents
54
55
56
57 @* An example of \cweb{}. This example, based on a program by
58 Klaus Guntermann and Joachim Schrod~\cite{litprog:schrod:cweb}
59 presents the ``word count'' program from \UNIX/, rewritten in
60 \cweb{} to demonstrate literate programming in \CEE/.%
61 \footnote{%
62 Incidentally, Klaus Guntermann and Joachim Schrod are now
63 using this \cweb{} and have stopped the support for their version.
64 Joachim Schrod contributed the \LaTeX{} style used for the markup of
65 this document.
66 }
67 The level of detail in this document is intentionally high, for
68 didactic purposes; many of the things spelled out here don't need to
69 be explained in other programs.
70
71 The purpose of \wc{} is to count lines, words, and/or characters in a
72 list of files. The number of lines in a file is the number of newline
73 characters it contains. The number of characters is the file length in bytes.
74 A ``word'' is a maximal sequence of consecutive characters other than
75 newline, space, or tab, containing at least one visible ASCII code.
76 (We assume that the standard ASCII code is in use.)
77
78 @ Most \cweb{} programs share a common structure. It's probably a
79 good idea to state the overall structure explicitly at the outset,
80 even though the various parts could all be introduced in unnamed
81 sections of the code if we wanted to add them piecemeal.
82
83 Here, then, is an overview of the file \texttt{wcltx.c} that is
84 defined by this \cweb{} program \texttt{wcltx.w}:
85
86 @c
87 @<Header files to include@>@/
88 @<Global variables@>@/
89 @<Functions@>@/
90 @<The main program@>
91
92 @ We must include the standard I/O definitions, since we want to send
93 formatted output to |stdout| and |stderr|.
94
95 @<Header files...@>=
96 #include <stdio.h>
97
98 @ The |status| variable will tell the operating system if the run was
99 successful or not, and |prog_name| is used in case there's an error message to
100 be printed.
101
102 @d OK 0 /* |status| code for successful run */
103 @d usage_error 1 /* |status| code for improper syntax */
104 @d cannot_open_file 2 /* |status| code for file access error */
105
106 @<Global variables@>=
107 int status=OK; /* exit status of command, initially |OK| */
108 char *prog_name; /* who we are */
109
110 @ Now we come to the general layout of the |main| function.
111
112 @<The main...@>=
113 main (argc,argv)
114 int argc; /* the number of arguments on the \UNIX/ command line */
115 char **argv; /* the arguments themselves, an array of strings */
116 {
117 @<Variables local to |main|@>@;
118 prog_name=argv[0];
119 @<Set up option selection@>;
120 @<Process all the files@>;
121 @<Print the grand totals if there were multiple files @>;
122 exit(status);
123 }
124
125 @ If the first argument begins with a `\texttt{-}', the user is choosing
126 the desired counts and specifying the order in which they should be
127 displayed. Each selection is given by the initial character
128 (lines, words, or characters). For example, `\texttt{-cl}' would cause
129 just the number of characters and the number of lines to be printed,
130 in that order.
131
132 We do not process this string now; we simply remember where it is.
133 It will be used to control the formatting at output time.
134
135 @<Var...@>=
136 int file_count; /* how many files there are */
137 char *which; /* which counts to print */
138
139 @ @<Set up o...@>=
140 which="lwc"; /* if no option is given, print all three values */
141 if (argc>1 && *argv[1] == '-') { which=argv[1]+1; argc--; argv++; }
142 file_count=argc-1;
143
144 @ Now we scan the remaining arguments and try to open a file, if
145 possible. The file is processed and its statistics are given.
146 We use a |do|~\dots~|while| loop because we should read from the
147 standard input if no file name is given.
148
149 @<Process...@>=
150 argc--;
151 do@+{
152 @<If a file is given, try to open |*(++argv)|; |continue| if unsuccessful@>;
153 @<Initialize pointers and counters@>;
154 @<Scan file@>;
155 @<Write statistics for file@>;
156 @<Close file@>;
157 @<Update grand totals@>; /* even if there is only one file */
158 }@+while (--argc>0);
159
160 @ Here's the code to open the file. A special trick allows us to
161 handle input from |stdin| when no name is given.
162 Recall that the file descriptor to |stdin| is~0; that's what we
163 use as the default initial value.
164
165 @<Variabl...@>=
166 int fd=0; /* file descriptor, initialized to |stdin| */
167
168 @ @d READ_ONLY 0 /* read access code for system |open| routine */
169
170 @<If a file...@>=
171 if (file_count>0 && (fd=open(*(++argv),READ_ONLY))<0) {
172 fprintf (stderr, "%s: cannot open file %s\n", prog_name, *argv);
173 @.cannot open file@>
174 status|=cannot_open_file;
175 file_count--;
176 continue;
177 }
178
179 @ @<Close file@>=
180 close(fd);
181
182 @ We will do some homemade buffering in order to speed things up: Characters
183 will be read into the |buffer| array before we process them.
184 To do this we set up appropriate pointers and counters.
185
186 @d buf_size BUFSIZ /* \texttt{stdio.h}'s |BUFSIZ| is chosen for efficiency */
187
188 @<Var...@>=
189 char buffer[buf_size]; /* we read the input into this array */
190 register char *ptr; /* the first unprocessed character in |buffer| */
191 register char *buf_end; /* the first unused position in |buffer| */
192 register int c; /* current character, or number of characters just read */
193 int in_word; /* are we within a word? */
194 long word_count, line_count, char_count; /* number of words, lines,
195 and characters found in the file so far */
196
197 @ @<Init...@>=
198 ptr=buf_end=buffer; line_count=word_count=char_count=0; in_word=0;
199
200 @ The grand totals must be initialized to zero at the beginning of the
201 program. If we made these variables local to |main|, we would have to
202 do this initialization explicitly; however, \CEE/'s globals are automatically
203 zeroed. (Or rather, ``statically zeroed.'') (Get it?)
204 @^Joke@>
205 %% -js: The joke would be better if the vars would be static, which
206 %% they aren't in the C sense...
207
208 @<Global var...@>=
209 long tot_word_count, tot_line_count, tot_char_count;
210 /* total number of words, lines, and chars */
211
212 @ The present section, which does the counting that is \wc{}'s \emph{raison
213 d'\^etre}, was actually one of the simplest to write. We look at each
214 character and change state if it begins or ends a word.
215
216 @<Scan...@>=
217 while (1) {
218 @<Fill |buffer| if it is empty; |break| at end of file@>;
219 c=*ptr++;
220 if (c>' ' && c<0177) { /* visible ASCII codes */
221 if (!in_word) {word_count++; in_word=1;}
222 continue;
223 }
224 if (c=='\n') line_count++;
225 else if (c!=' ' && c!='\t') continue;
226 in_word=0; /* |c| is newline, space, or tab */
227 }
228
229 @ Buffered I/O allows us to count the number of characters almost for free.
230
231 @<Fill |buff...@>=
232 if (ptr>=buf_end) {
233 ptr=buffer; c=read(fd,ptr,buf_size);
234 if (c<=0) break;
235 char_count+=c; buf_end=buffer+c;
236 }
237
238 @ It's convenient to output the statistics by defining a new function
239 |wc_print|; then the same function can be used for the totals.
240 Additionally we must decide here if we know the name of the file
241 we have processed or if it was just |stdin|.
242
243 @<Write...@>=
244 wc_print(which, char_count, word_count, line_count);
245 if (file_count) printf (" %s\n", *argv); /* not |stdin| */
246 else printf ("\n"); /* |stdin| */
247
248 @ @<Upda...@>=
249 tot_line_count+=line_count;
250 tot_word_count+=word_count;
251 tot_char_count+=char_count;
252
253 @ We might as well improve a bit on \UNIX/'s \wc{} by displaying the
254 number of files too.
255
256 @<Print the...@>=
257 if (file_count>1) {
258 wc_print(which, tot_char_count, tot_word_count, tot_line_count);
259 printf(" total in %d files\n",file_count);
260 }
261
262 @ Here now is the function that prints the values according to the
263 specified options. The calling routine is supposed to supply a
264 newline. If an invalid option character is found we inform
265 the user about proper usage of the command. Counts are printed in
266 8-digit fields so that they will line up in columns.
267
268 @d print_count(n) printf("%8ld",n)
269
270 @<Fun...@>=
271 wc_print(which, char_count, word_count, line_count)
272 char *which; /* which counts to print */
273 long char_count, word_count, line_count; /* given totals */
274 {
275 while (*which)
276 switch (*which++) {
277 case 'l': print_count(line_count); break;
278 case 'w': print_count(word_count); break;
279 case 'c': print_count(char_count); break;
280 default: if ((status & usage_error)==0) {
281 fprintf (stderr, "\nUsage: %s [-lwc] [filename ...]\n", prog_name);
282 @.Usage: ...@>
283 status|=usage_error;
284 }
285 }
286 }
287
288 @ Incidentally, a test of this program against the system \wc{}
289 command on a \SPARC\ showed that the ``official'' \wc{} was slightly
290 slower. Furthermore, although that \wc{} gave an appropriate error
291 message for the options `\texttt{-abc}', it made no complaints about the
292 options `\texttt{-labc}'! Dare we suggest that the system routine
293 might have been
294 better if its programmer had used a more literate approach?
295
296
297
298 \bibliographystyle{plain}
299 \bibliography{wcltx}
300
301
302 @
303
304 \cwebIndexIntro{%
305 Here is a list of the identifiers used, and where they appear.
306 Underlined entries indicate the place of definition. Error messages
307 are also shown.
308 }
309
310 \end{document}
311
312
313 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
314 %
315 % $Log: wcltx.w,v $
316 % Revision 1.4 1995/08/29 17:27:57 schrod
317 % Recoded to LaTeX2e markup.
318 %
319 % Revision 1.3 1993/06/15 14:01:14 schrod
320 % Renamed document to wcltx, must change \bibliography tag, too.
321 %
322 % Revision 1.2 1993/06/15 13:35:12 schrod
323 % `cweb' is now a style, was an option formerly.
324 %
325 % Revision 1.1 1993/04/09 15:00:37 schrod
326 % Initial revision
327 %