strings.c 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. /* vi: set sw=4 ts=4: */
  2. /*
  3. * strings implementation for busybox
  4. *
  5. * Copyright Tito Ragusa <farmatito@tiscali.it>
  6. *
  7. * Licensed under the GPL v2 or later, see the file LICENSE in this tarball.
  8. */
  9. #include <getopt.h>
  10. #include "libbb.h"
  11. #define WHOLE_FILE 1
  12. #define PRINT_NAME 2
  13. #define PRINT_OFFSET 4
  14. #define SIZE 8
  15. int strings_main(int argc, char **argv);
  16. int strings_main(int argc, char **argv)
  17. {
  18. int n, c, i = 0, status = EXIT_SUCCESS;
  19. unsigned opt;
  20. unsigned long count;
  21. FILE *file = stdin;
  22. char *string;
  23. const char *fmt = "%s: ";
  24. const char *n_arg = "4";
  25. opt = getopt32(argc, argv, "afon:", &n_arg);
  26. /* -a is our default behaviour */
  27. argc -= optind;
  28. argv += optind;
  29. n = xatoul_range(n_arg, 1, INT_MAX);
  30. string = xzalloc(n + 1);
  31. n--;
  32. if (argc == 0) {
  33. fmt = "{%s}: ";
  34. *argv = (char *)bb_msg_standard_input;
  35. goto PIPE;
  36. }
  37. do {
  38. file = fopen_or_warn(*argv, "r");
  39. if (file) {
  40. PIPE:
  41. count = 0;
  42. do {
  43. c = fgetc(file);
  44. if (isprint(c) || c == '\t') {
  45. if (i <= n) {
  46. string[i] = c;
  47. } else {
  48. putchar(c);
  49. }
  50. if (i == n) {
  51. if (opt & PRINT_NAME) {
  52. printf(fmt, *argv);
  53. }
  54. if (opt & PRINT_OFFSET) {
  55. printf("%7lo ", count - n);
  56. }
  57. printf("%s", string);
  58. }
  59. i++;
  60. } else {
  61. if (i > n) {
  62. putchar('\n');
  63. }
  64. i = 0;
  65. }
  66. count++;
  67. } while (c != EOF);
  68. fclose_if_not_stdin(file);
  69. } else {
  70. status = EXIT_FAILURE;
  71. }
  72. } while (--argc > 0);
  73. if (ENABLE_FEATURE_CLEAN_UP)
  74. free(string);
  75. fflush_stdout_and_exit(status);
  76. }