catv.c 1.9 KB

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