catv.c 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  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. #define CATV_OPT_e (1<<0)
  20. #define CATV_OPT_t (1<<1)
  21. #define CATV_OPT_v (1<<2)
  22. struct BUG_const_mismatch {
  23. char BUG_const_mismatch[
  24. CATV_OPT_e == VISIBLE_ENDLINE && CATV_OPT_t == VISIBLE_SHOW_TABS
  25. ? 1 : -1
  26. ];
  27. };
  28. int catv_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  29. int catv_main(int argc UNUSED_PARAM, char **argv)
  30. {
  31. int retval = EXIT_SUCCESS;
  32. int fd;
  33. unsigned opts;
  34. opts = getopt32(argv, "etv");
  35. argv += optind;
  36. #if 0 /* These consts match, we can just pass "opts" to visible() */
  37. if (opts & CATV_OPT_e)
  38. flags |= VISIBLE_ENDLINE;
  39. if (opts & CATV_OPT_t)
  40. flags |= VISIBLE_SHOW_TABS;
  41. #endif
  42. /* Read from stdin if there's nothing else to do. */
  43. if (!argv[0])
  44. *--argv = (char*)"-";
  45. do {
  46. fd = open_or_warn_stdin(*argv);
  47. if (fd < 0) {
  48. retval = EXIT_FAILURE;
  49. continue;
  50. }
  51. for (;;) {
  52. int i, res;
  53. #define read_buf bb_common_bufsiz1
  54. res = read(fd, read_buf, COMMON_BUFSIZE);
  55. if (res < 0)
  56. retval = EXIT_FAILURE;
  57. if (res <= 0)
  58. break;
  59. for (i = 0; i < res; i++) {
  60. unsigned char c = read_buf[i];
  61. if (opts & CATV_OPT_v) {
  62. putchar(c);
  63. } else {
  64. char buf[sizeof("M-^c")];
  65. visible(c, buf, opts);
  66. fputs(buf, stdout);
  67. }
  68. }
  69. }
  70. if (ENABLE_FEATURE_CLEAN_UP && fd)
  71. close(fd);
  72. } while (*++argv);
  73. fflush_stdout_and_exit(retval);
  74. }