catv.c 1.8 KB

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