1 /* wc.c - Word count
2 *
3 * Copyright 2011 Rob Landley <rob@landley.net>
4 *
5 * See http://opengroup.org/onlinepubs/9699919799/utilities/wc.html
6
7 USE_WC(NEWTOY(wc, USE_TOYBOX_I18N("m")"cwl", TOYFLAG_USR|TOYFLAG_BIN|TOYFLAG_LOCALE))
8
9 config WC
10 bool "wc"
11 default y
12 help
13 usage: wc -lwcm [FILE...]
14
15 Count lines, words, and characters in input.
16
17 -l show lines
18 -w show words
19 -c show bytes
20 -m show characters
21
22 By default outputs lines, words, bytes, and filename for each
23 argument (or from stdin if none). Displays only either bytes
24 or characters.
25 */
26
27 #define FOR_wc
28 #include "toys.h"
29
GLOBALS(unsigned long totals[3];)30 GLOBALS(
31 unsigned long totals[3];
32 )
33
34 static void show_lengths(unsigned long *lengths, char *name)
35 {
36 int i, nospace = 1;
37 for (i=0; i<3; i++) {
38 if (!toys.optflags || (toys.optflags&(1<<i))) {
39 xprintf(" %ld"+nospace, lengths[i]);
40 nospace = 0;
41 }
42 TT.totals[i] += lengths[i];
43 }
44 if (*toys.optargs) xprintf(" %s", name);
45 xputc('\n');
46 }
47
do_wc(int fd,char * name)48 static void do_wc(int fd, char *name)
49 {
50 int i, len, clen=1, space;
51 unsigned long word=0, lengths[]={0,0,0};
52
53 for (;;) {
54 len = read(fd, toybuf, sizeof(toybuf));
55 if (len<0) perror_msg("%s", name);
56 if (len<1) break;
57 for (i=0; i<len; i+=clen) {
58 wchar_t wchar;
59
60 if (CFG_TOYBOX_I18N && (toys.optflags&FLAG_m)) {
61 clen = mbrtowc(&wchar, toybuf+i, len-i, 0);
62 if (clen == -1) {
63 clen = 1;
64 continue;
65 }
66 if (clen == -2) break;
67 if (clen == 0) clen=1;
68 space = iswspace(wchar);
69 } else space = isspace(toybuf[i]);
70
71 if (toybuf[i]==10) lengths[0]++;
72 if (space) word=0;
73 else {
74 if (!word) lengths[1]++;
75 word=1;
76 }
77 lengths[2]++;
78 }
79 }
80
81 show_lengths(lengths, name);
82 }
83
wc_main(void)84 void wc_main(void)
85 {
86 toys.optflags |= (toys.optflags&8)>>1;
87 loopfiles(toys.optargs, do_wc);
88 if (toys.optc>1) show_lengths(TT.totals, "total");
89 }
90