strings.c 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  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) MAIN_EXTERNALLY_VISIBLE;
  16. int strings_main(int argc, char **argv)
  17. {
  18. int n, c, status = EXIT_SUCCESS;
  19. unsigned opt;
  20. unsigned count;
  21. off_t offset;
  22. FILE *file = stdin;
  23. char *string;
  24. const char *fmt = "%s: ";
  25. const char *n_arg = "4";
  26. opt = getopt32(argv, "afon:", &n_arg);
  27. /* -a is our default behaviour */
  28. /*argc -= optind;*/
  29. argv += optind;
  30. n = xatou_range(n_arg, 1, INT_MAX);
  31. string = xzalloc(n + 1);
  32. n--;
  33. if (!*argv) {
  34. fmt = "{%s}: ";
  35. *--argv = (char *)bb_msg_standard_input;
  36. goto PIPE;
  37. }
  38. do {
  39. file = fopen_or_warn(*argv, "r");
  40. if (!file) {
  41. status = EXIT_FAILURE;
  42. continue;
  43. }
  44. PIPE:
  45. offset = 0;
  46. count = 0;
  47. do {
  48. c = fgetc(file);
  49. if (isprint(c) || c == '\t') {
  50. if (count > n) {
  51. bb_putchar(c);
  52. } else {
  53. string[count] = c;
  54. if (count == n) {
  55. if (opt & PRINT_NAME) {
  56. printf(fmt, *argv);
  57. }
  58. if (opt & PRINT_OFFSET) {
  59. printf("%7"OFF_FMT"o ", offset - n);
  60. }
  61. fputs(string, stdout);
  62. }
  63. count++;
  64. }
  65. } else {
  66. if (count > n) {
  67. bb_putchar('\n');
  68. }
  69. count = 0;
  70. }
  71. offset++;
  72. } while (c != EOF);
  73. fclose_if_not_stdin(file);
  74. } while (*++argv);
  75. if (ENABLE_FEATURE_CLEAN_UP)
  76. free(string);
  77. fflush_stdout_and_exit(status);
  78. }