wc.c 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241
  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: "\nOptions:"
  62. //usage: "\n -c Count bytes"
  63. //usage: IF_UNICODE_SUPPORT(
  64. //usage: "\n -m Count characters"
  65. //usage: )
  66. //usage: "\n -l Count newlines"
  67. //usage: "\n -w Count words"
  68. //usage: "\n -L Print longest line length"
  69. //usage:
  70. //usage:#define wc_example_usage
  71. //usage: "$ wc /etc/passwd\n"
  72. //usage: " 31 46 1365 /etc/passwd\n"
  73. /* Order is important if we want to be compatible with
  74. * column order in "wc -cmlwL" output:
  75. */
  76. enum {
  77. WC_LINES = 0, /* -l */
  78. WC_WORDS = 1, /* -w */
  79. WC_UNICHARS = 2, /* -m */
  80. WC_BYTES = 3, /* -c */
  81. WC_LENGTH = 4, /* -L */
  82. NUM_WCS = 5,
  83. };
  84. int wc_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  85. int wc_main(int argc UNUSED_PARAM, char **argv)
  86. {
  87. const char *arg;
  88. const char *start_fmt = " %9"COUNT_FMT + 1;
  89. const char *fname_fmt = " %s\n";
  90. COUNT_T *pcounts;
  91. COUNT_T counts[NUM_WCS];
  92. COUNT_T totals[NUM_WCS];
  93. int num_files;
  94. smallint status = EXIT_SUCCESS;
  95. unsigned print_type;
  96. init_unicode();
  97. print_type = getopt32(argv, "lwmcL");
  98. if (print_type == 0) {
  99. print_type = (1 << WC_LINES) | (1 << WC_WORDS) | (1 << WC_BYTES);
  100. }
  101. argv += optind;
  102. if (!argv[0]) {
  103. *--argv = (char *) bb_msg_standard_input;
  104. fname_fmt = "\n";
  105. }
  106. if (!argv[1]) { /* zero or one filename? */
  107. if (!((print_type-1) & print_type)) /* exactly one option? */
  108. start_fmt = "%"COUNT_FMT;
  109. }
  110. memset(totals, 0, sizeof(totals));
  111. pcounts = counts;
  112. num_files = 0;
  113. while ((arg = *argv++) != NULL) {
  114. FILE *fp;
  115. const char *s;
  116. unsigned u;
  117. unsigned linepos;
  118. smallint in_word;
  119. ++num_files;
  120. fp = fopen_or_warn_stdin(arg);
  121. if (!fp) {
  122. status = EXIT_FAILURE;
  123. continue;
  124. }
  125. memset(counts, 0, sizeof(counts));
  126. linepos = 0;
  127. in_word = 0;
  128. while (1) {
  129. int c;
  130. /* Our -w doesn't match GNU wc exactly... oh well */
  131. c = getc(fp);
  132. if (c == EOF) {
  133. if (ferror(fp)) {
  134. bb_simple_perror_msg(arg);
  135. status = EXIT_FAILURE;
  136. }
  137. goto DO_EOF; /* Treat an EOF as '\r'. */
  138. }
  139. /* Cater for -c and -m */
  140. ++counts[WC_BYTES];
  141. if (unicode_status != UNICODE_ON /* every byte is a new char */
  142. || (c & 0xc0) != 0x80 /* it isn't a 2nd+ byte of a Unicode char */
  143. ) {
  144. ++counts[WC_UNICHARS];
  145. }
  146. if (isprint_asciionly(c)) { /* FIXME: not unicode-aware */
  147. ++linepos;
  148. if (!isspace(c)) {
  149. in_word = 1;
  150. continue;
  151. }
  152. } else if ((unsigned)(c - 9) <= 4) {
  153. /* \t 9
  154. * \n 10
  155. * \v 11
  156. * \f 12
  157. * \r 13
  158. */
  159. if (c == '\t') {
  160. linepos = (linepos | 7) + 1;
  161. } else { /* '\n', '\r', '\f', or '\v' */
  162. DO_EOF:
  163. if (linepos > counts[WC_LENGTH]) {
  164. counts[WC_LENGTH] = linepos;
  165. }
  166. if (c == '\n') {
  167. ++counts[WC_LINES];
  168. }
  169. if (c != '\v') {
  170. linepos = 0;
  171. }
  172. }
  173. } else {
  174. continue;
  175. }
  176. counts[WC_WORDS] += in_word;
  177. in_word = 0;
  178. if (c == EOF) {
  179. break;
  180. }
  181. }
  182. fclose_if_not_stdin(fp);
  183. if (totals[WC_LENGTH] < counts[WC_LENGTH]) {
  184. totals[WC_LENGTH] = counts[WC_LENGTH];
  185. }
  186. totals[WC_LENGTH] -= counts[WC_LENGTH];
  187. OUTPUT:
  188. /* coreutils wc tries hard to print pretty columns
  189. * (saves results for all files, finds max col len etc...)
  190. * we won't try that hard, it will bloat us too much */
  191. s = start_fmt;
  192. u = 0;
  193. do {
  194. if (print_type & (1 << u)) {
  195. printf(s, pcounts[u]);
  196. s = " %9"COUNT_FMT; /* Ok... restore the leading space. */
  197. }
  198. totals[u] += pcounts[u];
  199. } while (++u < NUM_WCS);
  200. printf(fname_fmt, arg);
  201. }
  202. /* If more than one file was processed, we want the totals. To save some
  203. * space, we set the pcounts ptr to the totals array. This has the side
  204. * effect of trashing the totals array after outputting it, but that's
  205. * irrelavent since we no longer need it. */
  206. if (num_files > 1) {
  207. num_files = 0; /* Make sure we don't get here again. */
  208. arg = "total";
  209. pcounts = totals;
  210. --argv;
  211. goto OUTPUT;
  212. }
  213. fflush_stdout_and_exit(status);
  214. }