3 * Copyright 2011 Rob Landley <rob@landley.net>
5 * See http://opengroup.org/onlinepubs/9699919799/utilities/wc.html
7 USE_WC(NEWTOY(wc, USE_TOYBOX_I18N("m")"cwl[!cm]", TOYFLAG_USR|TOYFLAG_BIN|TOYFLAG_LOCALE))
13 usage: wc -lwcm [FILE...]
15 Count lines, words, and characters in input.
22 By default outputs lines, words, bytes, and filename for each
23 argument (or from stdin if none). Displays only either bytes
31 unsigned long totals[3];
34 static void show_lengths(unsigned long *lengths, char *name)
38 if (!toys.optflags || (toys.optflags&(1<<i))) {
39 xprintf(" %ld"+nospace, lengths[i]);
42 TT.totals[i] += lengths[i];
44 if (*toys.optargs) xprintf(" %s", name);
48 static void do_wc(int fd, char *name)
50 int i, len, clen=1, space;
51 unsigned long word=0, lengths[]={0,0,0};
53 if (toys.optflags == FLAG_c) {
56 // On Linux, files in /proc often report their size as 0.
57 if (!fstat(fd, &st) && S_ISREG(st.st_mode) && st.st_size > 0) {
58 lengths[2] = st.st_size;
64 len = read(fd, toybuf, sizeof(toybuf));
65 if (len<0) perror_msg_raw(name);
67 if (toys.optflags == FLAG_c) {
71 for (i=0; i<len; i+=clen) {
74 if (CFG_TOYBOX_I18N && (toys.optflags&FLAG_m)) {
75 clen = mbrtowc(&wchar, toybuf+i, len-i, 0);
80 if (clen == -2) break;
81 if (clen == 0) clen=1;
82 space = iswspace(wchar);
83 } else space = isspace(toybuf[i]);
85 if (toybuf[i]==10) lengths[0]++;
88 if (!word) lengths[1]++;
96 show_lengths(lengths, name);
101 toys.optflags |= (toys.optflags&8)>>1;
102 loopfiles(toys.optargs, do_wc);
103 if (toys.optc>1) show_lengths(TT.totals, "total");