3
0

catv.c 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  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 tarball for details.
  8. */
  9. /* See "Cat -v considered harmful" at
  10. * http://cm.bell-labs.com/cm/cs/doc/84/kp.ps.gz */
  11. #include "busybox.h"
  12. int catv_main(int argc, char **argv)
  13. {
  14. int retval = EXIT_SUCCESS, fd;
  15. unsigned flags;
  16. flags = getopt32(argc, argv, "etv");
  17. #define CATV_OPT_e (1<<0)
  18. #define CATV_OPT_t (1<<1)
  19. #define CATV_OPT_v (1<<2)
  20. flags ^= CATV_OPT_v;
  21. argv += optind;
  22. do {
  23. /* Read from stdin if there's nothing else to do. */
  24. fd = 0;
  25. if (*argv && 0 > (fd = xopen(*argv, O_RDONLY)))
  26. retval = EXIT_FAILURE;
  27. else for (;;) {
  28. int i, res;
  29. res = read(fd, bb_common_bufsiz1, sizeof(bb_common_bufsiz1));
  30. if (res < 0)
  31. retval = EXIT_FAILURE;
  32. if (res < 1)
  33. break;
  34. for (i = 0; i < res; i++) {
  35. char c = bb_common_bufsiz1[i];
  36. if (c > 126 && (flags & CATV_OPT_v)) {
  37. if (c == 127) {
  38. printf("^?");
  39. continue;
  40. } else {
  41. printf("M-");
  42. c -= 128;
  43. }
  44. }
  45. if (c < 32) {
  46. if (c == 10) {
  47. if (flags & CATV_OPT_e)
  48. putchar('$');
  49. } else if (flags & (c==9 ? CATV_OPT_t : CATV_OPT_v)) {
  50. printf("^%c", c+'@');
  51. continue;
  52. }
  53. }
  54. putchar(c);
  55. }
  56. }
  57. if (ENABLE_FEATURE_CLEAN_UP && fd)
  58. close(fd);
  59. } while (*++argv);
  60. fflush_stdout_and_exit(retval);
  61. }