cat.c 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. /* cat.c - copy inputs to stdout.
  2. *
  3. * Copyright 2006 Rob Landley <rob@landley.net>
  4. *
  5. * See http://opengroup.org/onlinepubs/9699919799/utilities/cat.html
  6. *
  7. * And "Cat -v considered harmful" at
  8. * http://cm.bell-labs.com/cm/cs/doc/84/kp.ps.gz
  9. USE_CAT(NEWTOY(cat, "u"USE_CAT_V("vte"), TOYFLAG_BIN))
  10. USE_CATV(NEWTOY(catv, USE_CATV("vte"), TOYFLAG_USR|TOYFLAG_BIN))
  11. config CAT
  12. bool "cat"
  13. default y
  14. help
  15. usage: cat [-u] [FILE...]
  16. Copy (concatenate) files to stdout. If no files listed, copy from stdin.
  17. Filename "-" is a synonym for stdin.
  18. -u Copy one byte at a time (slow)
  19. config CAT_V
  20. bool "cat -etv"
  21. default n
  22. depends on CAT
  23. help
  24. usage: cat [-evt]
  25. -e Mark each newline with $
  26. -t Show tabs as ^I
  27. -v Display nonprinting characters as escape sequences with M-x for
  28. high ascii characters (>127), and ^x for other nonprinting chars
  29. config CATV
  30. bool "catv"
  31. default y
  32. help
  33. usage: catv [-evt] [FILE...]
  34. Display nonprinting characters as escape sequences. Use M-x for
  35. high ascii characters (>127), and ^x for other nonprinting chars.
  36. -e Mark each newline with $
  37. -t Show tabs as ^I
  38. -v Don't use ^x or M-x escapes
  39. */
  40. #define FOR_cat
  41. #define FORCE_FLAGS
  42. #include "toys.h"
  43. static void do_cat(int fd, char *name)
  44. {
  45. int i, len, size=(toys.optflags & FLAG_u) ? 1 : sizeof(toybuf);
  46. for(;;) {
  47. len = read(fd, toybuf, size);
  48. if (len < 0) {
  49. toys.exitval = EXIT_FAILURE;
  50. perror_msg_raw(name);
  51. }
  52. if (len < 1) break;
  53. if ((CFG_CAT_V || CFG_CATV) && (toys.optflags&~FLAG_u)) {
  54. for (i=0; i<len; i++) {
  55. char c=toybuf[i];
  56. if (c > 126 && (toys.optflags & FLAG_v)) {
  57. if (c > 127) {
  58. printf("M-");
  59. c -= 128;
  60. }
  61. if (c == 127) {
  62. printf("^?");
  63. continue;
  64. }
  65. }
  66. if (c < 32) {
  67. if (c == 10) {
  68. if (toys.optflags & FLAG_e) xputc('$');
  69. } else if (toys.optflags & (c==9 ? FLAG_t : FLAG_v)) {
  70. printf("^%c", c+'@');
  71. continue;
  72. }
  73. }
  74. xputc(c);
  75. }
  76. } else xwrite(1, toybuf, len);
  77. }
  78. }
  79. void cat_main(void)
  80. {
  81. loopfiles(toys.optargs, do_cat);
  82. }
  83. void catv_main(void)
  84. {
  85. toys.optflags ^= FLAG_v;
  86. loopfiles(toys.optargs, do_cat);
  87. }