3
0

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