catv.c 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  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. //usage:#define catv_trivial_usage
  12. //usage: "[-etv] [FILE]..."
  13. //usage:#define catv_full_usage "\n\n"
  14. //usage: "Display nonprinting characters as ^x or M-x\n"
  15. //usage: "\n -e End each line with $"
  16. //usage: "\n -t Show tabs as ^I"
  17. //usage: "\n -v Don't use ^x or M-x escapes"
  18. #include "libbb.h"
  19. #include "common_bufsiz.h"
  20. #define CATV_OPT_e (1<<0)
  21. #define CATV_OPT_t (1<<1)
  22. #define CATV_OPT_v (1<<2)
  23. struct BUG_const_mismatch {
  24. char BUG_const_mismatch[
  25. CATV_OPT_e == VISIBLE_ENDLINE && CATV_OPT_t == VISIBLE_SHOW_TABS
  26. ? 1 : -1
  27. ];
  28. };
  29. int catv_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  30. int catv_main(int argc UNUSED_PARAM, char **argv)
  31. {
  32. int retval = EXIT_SUCCESS;
  33. int fd;
  34. unsigned opts;
  35. opts = getopt32(argv, "etv");
  36. argv += optind;
  37. #if 0 /* These consts match, we can just pass "opts" to visible() */
  38. if (opts & CATV_OPT_e)
  39. flags |= VISIBLE_ENDLINE;
  40. if (opts & CATV_OPT_t)
  41. flags |= VISIBLE_SHOW_TABS;
  42. #endif
  43. /* Read from stdin if there's nothing else to do. */
  44. if (!argv[0])
  45. *--argv = (char*)"-";
  46. #define read_buf bb_common_bufsiz1
  47. setup_common_bufsiz();
  48. do {
  49. fd = open_or_warn_stdin(*argv);
  50. if (fd < 0) {
  51. retval = EXIT_FAILURE;
  52. continue;
  53. }
  54. for (;;) {
  55. int i, res;
  56. res = read(fd, read_buf, COMMON_BUFSIZE);
  57. if (res < 0)
  58. retval = EXIT_FAILURE;
  59. if (res <= 0)
  60. break;
  61. for (i = 0; i < res; i++) {
  62. unsigned char c = read_buf[i];
  63. if (opts & CATV_OPT_v) {
  64. putchar(c);
  65. } else {
  66. char buf[sizeof("M-^c")];
  67. visible(c, buf, opts);
  68. fputs(buf, stdout);
  69. }
  70. }
  71. }
  72. if (ENABLE_FEATURE_CLEAN_UP && fd)
  73. close(fd);
  74. } while (*++argv);
  75. fflush_stdout_and_exit(retval);
  76. }