program wordcount_pas; (* wordcount -- count words in standerd input or file bibliography 'Software Tools' B.W.Kernighan & P.J.Plauger 'The C Programming Language' B.W.Kernighan & D.M.Ritchie revision history: 1.0: ???. ??, 1986 2.0: Feb. 25, 1987 2.1: Mar. 8, 1987 2.2: Mar. 11, 1987 2.3: Mar. 30, 1987 2.4: Apr. 5, 1987 2.5: Nov. 23, 1987 2.6: Jun. 26, 1988 *) const YES = TRUE; NO = FALSE; NEWLINE = 10; BLANK = ' '; TAB = 9; DELIMIT: set of char = [^I, ^J, ^M, BLANK]; OPTCHAR = '-'; { char. of option } LINEOP = 'L'; { count line option } WORDOP = 'W'; { count word option } CHAROP = 'C'; { count charactor option } OPTMSG = '[-lwc] [file] [ [-lwc] [file] ... ]'; type str = string[255]; var argptr, i: integer; infile: text; lines, words, chars: boolean; tl, tw, tc: real; {$I stdio.lib} (* get switches *) procedure getswitch(var i: integer); var s: str; procedure checkopt(s: str); var i: integer; begin if s = OPTCHAR then begin writeln(stderr, 'Usage: ', argv(0), OPTMSG); exit(1); end else begin for i := 2 to length(s) do begin case s[i] of LINEOP: lines := YES; WORDOP: words := YES; CHAROP: chars := YES; else begin writeln(stderr, 'Usage: ', argv(0), OPTMSG); exit(1); end; end; { of case } end; { of for } end; end; { of checkopt } (* getswitch main *) begin s := argv(i); if (i <= argc) and (s[1] = OPTCHAR) then begin lines := NO; words := NO; chars := NO; repeat begin checkopt(s); i := i + 1; s := argv(i); end; until s[1] <> OPTCHAR; end; end; { of getswitch } (* count words in file *) procedure wordcount(var filvar: text); var ch: char; nl, nw, nc: real; { long integer } inword: boolean; begin inword := NO; nl := 0; nw := 0; nc := 0; while not eof(filvar) do begin read(filvar, ch); nc := nc + 1; if ch = chr(NEWLINE) then nl := nl + 1; if ch in DELIMIT then inword := NO else if inword = NO then begin inword := YES; nw := nw + 1; end; end; tl := tl + nl; tw := tw + nw; tc := tc + nc; if lines then write(stdout, nl :8 :0); if words then write(stdout, nw :8 :0); if chars then write(stdout, nc :8 :0); end; { of wordcount } (* main *) begin openstd; tl := 0; tw := 0; tc := 0; argptr := 1; lines := YES; words := YES; chars := YES; getswitch(argptr); if argptr >= (argc + 1) then begin wordcount(stdin); writeln(stdout); end else begin i := argptr; while i <= argc do begin openf(infile, argv(i), 'r'); wordcount(infile); write(stdout, ' '); writeln(stdout, argv(i)); close(infile); i := i + 1; getswitch(i); end; if (i > argptr + 1) and lines then write(stdout, tl :8 :0); if (i > argptr + 1) and words then write(stdout, tw :8 :0); if (i > argptr + 1) and chars then write(stdout, tc :8 :0); if (i > argptr + 1) then writeln(stdout, ' total'); end; exit(0); end. { of program }