78a5105da17661450c804760817307abdde77c5c
[oweals/busybox.git] / coreutils / wc.c
1 /* vi: set sw=4 ts=4: */
2 /*
3  * wc implementation for busybox
4  *
5  * Copyright (C) 2003  Manuel Novoa III  <mjn3@codepoet.org>
6  *
7  * Licensed under GPLv2 or later, see file LICENSE in this tarball for details.
8  */
9
10 /* BB_AUDIT SUSv3 _NOT_ compliant -- option -m is not currently supported. */
11 /* http://www.opengroup.org/onlinepubs/007904975/utilities/wc.html */
12
13 /* Mar 16, 2003      Manuel Novoa III   (mjn3@codepoet.org)
14  *
15  * Rewritten to fix a number of problems and do some size optimizations.
16  * Problems in the previous busybox implementation (besides bloat) included:
17  *  1) broken 'wc -c' optimization (read note below)
18  *  2) broken handling of '-' args
19  *  3) no checking of ferror on EOF returns
20  *  4) isprint() wasn't considered when word counting.
21  *
22  * TODO:
23  *
24  * When locale support is enabled, count multibyte chars in the '-m' case.
25  *
26  * NOTES:
27  *
28  * The previous busybox wc attempted an optimization using stat for the
29  * case of counting chars only.  I omitted that because it was broken.
30  * It didn't take into account the possibility of input coming from a
31  * pipe, or input from a file with file pointer not at the beginning.
32  *
33  * To implement such a speed optimization correctly, not only do you
34  * need the size, but also the file position.  Note also that the
35  * file position may be past the end of file.  Consider the example
36  * (adapted from example in gnu wc.c)
37  *
38  *      echo hello > /tmp/testfile &&
39  *      (dd ibs=1k skip=1 count=0 &> /dev/null ; wc -c) < /tmp/testfile
40  *
41  * for which 'wc -c' should output '0'.
42  */
43
44 #include "busybox.h"
45
46 #ifdef CONFIG_LOCALE_SUPPORT
47 #include <locale.h>
48 #include <ctype.h>
49 #define isspace_given_isprint(c) isspace(c)
50 #else
51 #undef isspace
52 #undef isprint
53 #define isspace(c) ((((c) == ' ') || (((unsigned int)((c) - 9)) <= (13 - 9))))
54 #define isprint(c) (((unsigned int)((c) - 0x20)) <= (0x7e - 0x20))
55 #define isspace_given_isprint(c) ((c) == ' ')
56 #endif
57
58 //#define COUNT_T unsigned long long
59 //#define COUNT_FMT "llu"
60 #define COUNT_T unsigned
61 #define COUNT_FMT "u"
62
63 enum {
64         WC_LINES        = 0,
65         WC_WORDS        = 1,
66         WC_CHARS        = 2,
67         WC_LENGTH       = 3
68 };
69
70 int wc_main(int argc, char **argv)
71 {
72         FILE *fp;
73         const char *s, *arg;
74         const char *start_fmt = "%9"COUNT_FMT;
75         const char *fname_fmt = " %s\n";
76         COUNT_T *pcounts;
77         COUNT_T counts[4];
78         COUNT_T totals[4];
79         unsigned linepos;
80         unsigned u;
81         int num_files = 0;
82         int c;
83         char status = EXIT_SUCCESS;
84         char in_word;
85         char print_type;
86
87         print_type = bb_getopt_ulflags(argc, argv, "lwcL");
88
89         if (print_type == 0) {
90                 print_type = (1 << WC_LINES) | (1 << WC_WORDS) | (1 << WC_CHARS);
91         }
92
93         argv += optind;
94         if (!argv[0]) {
95                 *--argv = (char *) bb_msg_standard_input;
96                 fname_fmt = "\n";
97                 if (!((print_type-1) & print_type)) /* exactly one option? */
98                         start_fmt = "%"COUNT_FMT;
99         }
100
101         memset(totals, 0, sizeof(totals));
102
103         pcounts = counts;
104
105         while ((arg = *argv++) != 0) {
106                 ++num_files;
107                 fp = bb_wfopen_input(arg);
108                 if (!fp) {
109                         status = EXIT_FAILURE;
110                         continue;
111                 }
112
113                 memset(counts, 0, sizeof(counts));
114                 linepos = 0;
115                 in_word = 0;
116
117                 do {
118                         ++counts[WC_CHARS];
119                         c = getc(fp);
120                         if (isprint(c)) {
121                                 ++linepos;
122                                 if (!isspace_given_isprint(c)) {
123                                         in_word = 1;
124                                         continue;
125                                 }
126                         } else if (((unsigned int)(c - 9)) <= 4) {
127                                 /* \t  9
128                                  * \n 10
129                                  * \v 11
130                                  * \f 12
131                                  * \r 13
132                                  */
133                                 if (c == '\t') {
134                                         linepos = (linepos | 7) + 1;
135                                 } else {                        /* '\n', '\r', '\f', or '\v' */
136                                 DO_EOF:
137                                         if (linepos > counts[WC_LENGTH]) {
138                                                 counts[WC_LENGTH] = linepos;
139                                         }
140                                         if (c == '\n') {
141                                                 ++counts[WC_LINES];
142                                         }
143                                         if (c != '\v') {
144                                                 linepos = 0;
145                                         }
146                                 }
147                         } else if (c == EOF) {
148                                 if (ferror(fp)) {
149                                         bb_perror_msg("%s", arg);
150                                         status = EXIT_FAILURE;
151                                 }
152                                 --counts[WC_CHARS];
153                                 goto DO_EOF;            /* Treat an EOF as '\r'. */
154                         } else {
155                                 continue;
156                         }
157
158                         counts[WC_WORDS] += in_word;
159                         in_word = 0;
160                         if (c == EOF) {
161                                 break;
162                         }
163                 } while (1);
164
165                 if (totals[WC_LENGTH] < counts[WC_LENGTH]) {
166                         totals[WC_LENGTH] = counts[WC_LENGTH];
167                 }
168                 totals[WC_LENGTH] -= counts[WC_LENGTH];
169
170                 bb_fclose_nonstdin(fp);
171
172         OUTPUT:
173                 /* coreutils wc tries hard to print pretty columns
174                  * (saves results for all files, find max col len etc...)
175                  * we won't try that hard, it will bloat us too much */
176                 s = start_fmt;
177                 u = 0;
178                 do {
179                         if (print_type & (1 << u)) {
180                                 bb_printf(s, pcounts[u]);
181                                 s = " %9"COUNT_FMT; /* Ok... restore the leading space. */
182                         }
183                         totals[u] += pcounts[u];
184                 } while (++u < 4);
185                 bb_printf(fname_fmt, arg);
186         }
187
188         /* If more than one file was processed, we want the totals.  To save some
189          * space, we set the pcounts ptr to the totals array.  This has the side
190          * effect of trashing the totals array after outputting it, but that's
191          * irrelavent since we no longer need it. */
192         if (num_files > 1) {
193                 num_files = 0;                          /* Make sure we don't get here again. */
194                 arg = "total";
195                 pcounts = totals;
196                 --argv;
197                 goto OUTPUT;
198         }
199
200         bb_fflush_stdout_and_exit(status);
201 }