3
0

catv.c 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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. #include "libbb.h"
  12. int catv_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  13. int catv_main(int argc UNUSED_PARAM, char **argv)
  14. {
  15. int retval = EXIT_SUCCESS;
  16. int fd;
  17. unsigned flags;
  18. flags = getopt32(argv, "etv");
  19. #define CATV_OPT_e (1<<0)
  20. #define CATV_OPT_t (1<<1)
  21. #define CATV_OPT_v (1<<2)
  22. flags ^= CATV_OPT_v;
  23. argv += optind;
  24. /* Read from stdin if there's nothing else to do. */
  25. if (!argv[0])
  26. *--argv = (char*)"-";
  27. do {
  28. fd = open_or_warn_stdin(*argv);
  29. if (fd < 0) {
  30. retval = EXIT_FAILURE;
  31. continue;
  32. }
  33. for (;;) {
  34. int i, res;
  35. #define read_buf bb_common_bufsiz1
  36. res = read(fd, read_buf, COMMON_BUFSIZE);
  37. if (res < 0)
  38. retval = EXIT_FAILURE;
  39. if (res < 1)
  40. break;
  41. for (i = 0; i < res; i++) {
  42. unsigned char c = read_buf[i];
  43. if (c > 126 && (flags & CATV_OPT_v)) {
  44. if (c == 127) {
  45. printf("^?");
  46. continue;
  47. }
  48. printf("M-");
  49. c -= 128;
  50. }
  51. if (c < 32) {
  52. if (c == 10) {
  53. if (flags & CATV_OPT_e)
  54. bb_putchar('$');
  55. } else if (flags & (c==9 ? CATV_OPT_t : CATV_OPT_v)) {
  56. printf("^%c", c+'@');
  57. continue;
  58. }
  59. }
  60. bb_putchar(c);
  61. }
  62. }
  63. if (ENABLE_FEATURE_CLEAN_UP && fd)
  64. close(fd);
  65. } while (*++argv);
  66. fflush_stdout_and_exit(retval);
  67. }