wc.c 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240
  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 source tree.
  8. */
  9. /* BB_AUDIT SUSv3 compliant. */
  10. /* http://www.opengroup.org/onlinepubs/007904975/utilities/wc.html */
  11. /* Mar 16, 2003 Manuel Novoa III (mjn3@codepoet.org)
  12. *
  13. * Rewritten to fix a number of problems and do some size optimizations.
  14. * Problems in the previous busybox implementation (besides bloat) included:
  15. * 1) broken 'wc -c' optimization (read note below)
  16. * 2) broken handling of '-' args
  17. * 3) no checking of ferror on EOF returns
  18. * 4) isprint() wasn't considered when word counting.
  19. *
  20. * NOTES:
  21. *
  22. * The previous busybox wc attempted an optimization using stat for the
  23. * case of counting chars only. I omitted that because it was broken.
  24. * It didn't take into account the possibility of input coming from a
  25. * pipe, or input from a file with file pointer not at the beginning.
  26. *
  27. * To implement such a speed optimization correctly, not only do you
  28. * need the size, but also the file position. Note also that the
  29. * file position may be past the end of file. Consider the example
  30. * (adapted from example in gnu wc.c)
  31. *
  32. * echo hello > /tmp/testfile &&
  33. * (dd ibs=1k skip=1 count=0 &> /dev/null; wc -c) < /tmp/testfile
  34. *
  35. * for which 'wc -c' should output '0'.
  36. */
  37. #include "libbb.h"
  38. #include "unicode.h"
  39. #if !ENABLE_LOCALE_SUPPORT
  40. # undef isprint
  41. # undef isspace
  42. # define isprint(c) ((unsigned)((c) - 0x20) <= (0x7e - 0x20))
  43. # define isspace(c) ((c) == ' ')
  44. #endif
  45. #if ENABLE_FEATURE_WC_LARGE
  46. # define COUNT_T unsigned long long
  47. # define COUNT_FMT "llu"
  48. #else
  49. # define COUNT_T unsigned
  50. # define COUNT_FMT "u"
  51. #endif
  52. /* We support -m even when UNICODE_SUPPORT is off,
  53. * we just don't advertise it in help text,
  54. * since it is the same as -c in this case.
  55. */
  56. //usage:#define wc_trivial_usage
  57. //usage: "[-c"IF_UNICODE_SUPPORT("m")"lwL] [FILE]..."
  58. //usage:
  59. //usage:#define wc_full_usage "\n\n"
  60. //usage: "Count lines, words, and bytes for each FILE (or stdin)\n"
  61. //usage: "\n -c Count bytes"
  62. //usage: IF_UNICODE_SUPPORT(
  63. //usage: "\n -m Count characters"
  64. //usage: )
  65. //usage: "\n -l Count newlines"
  66. //usage: "\n -w Count words"
  67. //usage: "\n -L Print longest line length"
  68. //usage:
  69. //usage:#define wc_example_usage
  70. //usage: "$ wc /etc/passwd\n"
  71. //usage: " 31 46 1365 /etc/passwd\n"
  72. /* Order is important if we want to be compatible with
  73. * column order in "wc -cmlwL" output:
  74. */
  75. enum {
  76. WC_LINES = 0, /* -l */
  77. WC_WORDS = 1, /* -w */
  78. WC_UNICHARS = 2, /* -m */
  79. WC_BYTES = 3, /* -c */
  80. WC_LENGTH = 4, /* -L */
  81. NUM_WCS = 5,
  82. };
  83. int wc_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  84. int wc_main(int argc UNUSED_PARAM, char **argv)
  85. {
  86. const char *arg;
  87. const char *start_fmt = " %9"COUNT_FMT + 1;
  88. const char *fname_fmt = " %s\n";
  89. COUNT_T *pcounts;
  90. COUNT_T counts[NUM_WCS];
  91. COUNT_T totals[NUM_WCS];
  92. int num_files;
  93. smallint status = EXIT_SUCCESS;
  94. unsigned print_type;
  95. init_unicode();
  96. print_type = getopt32(argv, "lwmcL");
  97. if (print_type == 0) {
  98. print_type = (1 << WC_LINES) | (1 << WC_WORDS) | (1 << WC_BYTES);
  99. }
  100. argv += optind;
  101. if (!argv[0]) {
  102. *--argv = (char *) bb_msg_standard_input;
  103. fname_fmt = "\n";
  104. }
  105. if (!argv[1]) { /* zero or one filename? */
  106. if (!((print_type-1) & print_type)) /* exactly one option? */
  107. start_fmt = "%"COUNT_FMT;
  108. }
  109. memset(totals, 0, sizeof(totals));
  110. pcounts = counts;
  111. num_files = 0;
  112. while ((arg = *argv++) != NULL) {
  113. FILE *fp;
  114. const char *s;
  115. unsigned u;
  116. unsigned linepos;
  117. smallint in_word;
  118. ++num_files;
  119. fp = fopen_or_warn_stdin(arg);
  120. if (!fp) {
  121. status = EXIT_FAILURE;
  122. continue;
  123. }
  124. memset(counts, 0, sizeof(counts));
  125. linepos = 0;
  126. in_word = 0;
  127. while (1) {
  128. int c;
  129. /* Our -w doesn't match GNU wc exactly... oh well */
  130. c = getc(fp);
  131. if (c == EOF) {
  132. if (ferror(fp)) {
  133. bb_simple_perror_msg(arg);
  134. status = EXIT_FAILURE;
  135. }
  136. goto DO_EOF; /* Treat an EOF as '\r'. */
  137. }
  138. /* Cater for -c and -m */
  139. ++counts[WC_BYTES];
  140. if (unicode_status != UNICODE_ON /* every byte is a new char */
  141. || (c & 0xc0) != 0x80 /* it isn't a 2nd+ byte of a Unicode char */
  142. ) {
  143. ++counts[WC_UNICHARS];
  144. }
  145. if (isprint_asciionly(c)) { /* FIXME: not unicode-aware */
  146. ++linepos;
  147. if (!isspace(c)) {
  148. in_word = 1;
  149. continue;
  150. }
  151. } else if ((unsigned)(c - 9) <= 4) {
  152. /* \t 9
  153. * \n 10
  154. * \v 11
  155. * \f 12
  156. * \r 13
  157. */
  158. if (c == '\t') {
  159. linepos = (linepos | 7) + 1;
  160. } else { /* '\n', '\r', '\f', or '\v' */
  161. DO_EOF:
  162. if (linepos > counts[WC_LENGTH]) {
  163. counts[WC_LENGTH] = linepos;
  164. }
  165. if (c == '\n') {
  166. ++counts[WC_LINES];
  167. }
  168. if (c != '\v') {
  169. linepos = 0;
  170. }
  171. }
  172. } else {
  173. continue;
  174. }
  175. counts[WC_WORDS] += in_word;
  176. in_word = 0;
  177. if (c == EOF) {
  178. break;
  179. }
  180. }
  181. fclose_if_not_stdin(fp);
  182. if (totals[WC_LENGTH] < counts[WC_LENGTH]) {
  183. totals[WC_LENGTH] = counts[WC_LENGTH];
  184. }
  185. totals[WC_LENGTH] -= counts[WC_LENGTH];
  186. OUTPUT:
  187. /* coreutils wc tries hard to print pretty columns
  188. * (saves results for all files, finds max col len etc...)
  189. * we won't try that hard, it will bloat us too much */
  190. s = start_fmt;
  191. u = 0;
  192. do {
  193. if (print_type & (1 << u)) {
  194. printf(s, pcounts[u]);
  195. s = " %9"COUNT_FMT; /* Ok... restore the leading space. */
  196. }
  197. totals[u] += pcounts[u];
  198. } while (++u < NUM_WCS);
  199. printf(fname_fmt, arg);
  200. }
  201. /* If more than one file was processed, we want the totals. To save some
  202. * space, we set the pcounts ptr to the totals array. This has the side
  203. * effect of trashing the totals array after outputting it, but that's
  204. * irrelavent since we no longer need it. */
  205. if (num_files > 1) {
  206. num_files = 0; /* Make sure we don't get here again. */
  207. arg = "total";
  208. pcounts = totals;
  209. --argv;
  210. goto OUTPUT;
  211. }
  212. fflush_stdout_and_exit(status);
  213. }