catv.c 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. /* vi: set sw=4 ts=4: */
  2. /*
  3. * cat -v implementation for busybox
  4. *
  5. * Copyright (C) 2006 Rob Landley <rob@landley.net>
  6. *
  7. * Licensed under GPLv2 or later, see file LICENSE in this source tree.
  8. */
  9. /* See "Cat -v considered harmful" at
  10. * http://cm.bell-labs.com/cm/cs/doc/84/kp.ps.gz */
  11. //config:config CATV
  12. //config: bool "catv"
  13. //config: default y
  14. //config: help
  15. //config: Display nonprinting characters as escape sequences (like some
  16. //config: implementations' cat -v option).
  17. //applet:IF_CATV(APPLET(catv, BB_DIR_BIN, BB_SUID_DROP))
  18. //kbuild:lib-$(CONFIG_CATV) += catv.o
  19. //usage:#define catv_trivial_usage
  20. //usage: "[-etv] [FILE]..."
  21. //usage:#define catv_full_usage "\n\n"
  22. //usage: "Display nonprinting characters as ^x or M-x\n"
  23. //usage: "\n -e End each line with $"
  24. //usage: "\n -t Show tabs as ^I"
  25. //usage: "\n -v Don't use ^x or M-x escapes"
  26. #include "libbb.h"
  27. #include "common_bufsiz.h"
  28. #define CATV_OPT_e (1<<0)
  29. #define CATV_OPT_t (1<<1)
  30. #define CATV_OPT_v (1<<2)
  31. struct BUG_const_mismatch {
  32. char BUG_const_mismatch[
  33. CATV_OPT_e == VISIBLE_ENDLINE && CATV_OPT_t == VISIBLE_SHOW_TABS
  34. ? 1 : -1
  35. ];
  36. };
  37. int catv_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  38. int catv_main(int argc UNUSED_PARAM, char **argv)
  39. {
  40. int retval = EXIT_SUCCESS;
  41. int fd;
  42. unsigned opts;
  43. opts = getopt32(argv, "etv");
  44. argv += optind;
  45. #if 0 /* These consts match, we can just pass "opts" to visible() */
  46. if (opts & CATV_OPT_e)
  47. flags |= VISIBLE_ENDLINE;
  48. if (opts & CATV_OPT_t)
  49. flags |= VISIBLE_SHOW_TABS;
  50. #endif
  51. /* Read from stdin if there's nothing else to do. */
  52. if (!argv[0])
  53. *--argv = (char*)"-";
  54. #define read_buf bb_common_bufsiz1
  55. setup_common_bufsiz();
  56. do {
  57. fd = open_or_warn_stdin(*argv);
  58. if (fd < 0) {
  59. retval = EXIT_FAILURE;
  60. continue;
  61. }
  62. for (;;) {
  63. int i, res;
  64. res = read(fd, read_buf, COMMON_BUFSIZE);
  65. if (res < 0)
  66. retval = EXIT_FAILURE;
  67. if (res <= 0)
  68. break;
  69. for (i = 0; i < res; i++) {
  70. unsigned char c = read_buf[i];
  71. if (opts & CATV_OPT_v) {
  72. putchar(c);
  73. } else {
  74. char buf[sizeof("M-^c")];
  75. visible(c, buf, opts);
  76. fputs(buf, stdout);
  77. }
  78. }
  79. }
  80. if (ENABLE_FEATURE_CLEAN_UP && fd)
  81. close(fd);
  82. } while (*++argv);
  83. fflush_stdout_and_exit(retval);
  84. }