3
0

catv.c 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  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 "libbb.h"
  12. int catv_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  13. int catv_main(int argc, 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. fd = 0;
  26. if (!argv[0]) {
  27. argv--;
  28. goto jump_in;
  29. }
  30. do {
  31. fd = open_or_warn(*argv, O_RDONLY);
  32. if (fd < 0) {
  33. retval = EXIT_FAILURE;
  34. continue;
  35. }
  36. jump_in:
  37. for (;;) {
  38. int i, res;
  39. #define read_buf bb_common_bufsiz1
  40. res = read(fd, read_buf, COMMON_BUFSIZE);
  41. if (res < 0)
  42. retval = EXIT_FAILURE;
  43. if (res < 1)
  44. break;
  45. for (i = 0; i < res; i++) {
  46. unsigned char c = read_buf[i];
  47. if (c > 126 && (flags & CATV_OPT_v)) {
  48. if (c == 127) {
  49. printf("^?");
  50. continue;
  51. }
  52. printf("M-");
  53. c -= 128;
  54. }
  55. if (c < 32) {
  56. if (c == 10) {
  57. if (flags & CATV_OPT_e)
  58. bb_putchar('$');
  59. } else if (flags & (c==9 ? CATV_OPT_t : CATV_OPT_v)) {
  60. printf("^%c", c+'@');
  61. continue;
  62. }
  63. }
  64. bb_putchar(c);
  65. }
  66. }
  67. if (ENABLE_FEATURE_CLEAN_UP && fd)
  68. close(fd);
  69. } while (*++argv);
  70. fflush_stdout_and_exit(retval);
  71. }