• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 
10 USE_CAT(NEWTOY(cat, "u"USE_CAT_V("vte"), TOYFLAG_BIN))
11 USE_CATV(NEWTOY(catv, USE_CATV("vte"), TOYFLAG_USR|TOYFLAG_BIN))
12 
13 config CAT
14   bool "cat"
15   default y
16   help
17     usage: cat [-u] [file...]
18 
19     Copy (concatenate) files to stdout.  If no files listed, copy from stdin.
20     Filename "-" is a synonym for stdin.
21 
22     -u	Copy one byte at a time (slow).
23 
24 config CAT_V
25   bool "cat -etv"
26   default n
27   depends on CAT
28   help
29     usage: cat [-evt]
30 
31     -e	Mark each newline with $
32     -t	Show tabs as ^I
33     -v	Display nonprinting characters as escape sequences. Use M-x for
34     	high ascii characters (>127), and ^x for other nonprinting chars.
35 
36 config CATV
37   bool "catv"
38   default y
39   help
40     usage: catv [-evt] [filename...]
41 
42     Display nonprinting characters as escape sequences. Use M-x for
43     high ascii characters (>127), and ^x for other nonprinting chars.
44 
45     -e  Mark each newline with $
46     -t  Show tabs as ^I
47     -v  Don't use ^x or M-x escapes.
48 */
49 
50 #define FOR_cat
51 #define FORCE_FLAGS
52 #include "toys.h"
53 
do_cat(int fd,char * name)54 static void do_cat(int fd, char *name)
55 {
56   int i, len, size=(toys.optflags & FLAG_u) ? 1 : sizeof(toybuf);
57 
58   for(;;) {
59     len = read(fd, toybuf, size);
60     if (len < 0) toys.exitval = EXIT_FAILURE;
61     if (len < 1) break;
62     if ((CFG_CAT_V || CFG_CATV) && (toys.optflags&~FLAG_u)) {
63       for (i=0; i<len; i++) {
64         char c=toybuf[i];
65 
66         if (c > 126 && (toys.optflags & FLAG_v)) {
67           if (c > 127) {
68             printf("M-");
69             c -= 128;
70           }
71           if (c == 127) {
72             printf("^?");
73             continue;
74           }
75         }
76         if (c < 32) {
77           if (c == 10) {
78             if (toys.optflags & FLAG_e) xputc('$');
79           } else if (toys.optflags & (c==9 ? FLAG_t : FLAG_v)) {
80             printf("^%c", c+'@');
81             continue;
82           }
83         }
84         xputc(c);
85       }
86     } else xwrite(1, toybuf, len);
87   }
88 }
89 
cat_main(void)90 void cat_main(void)
91 {
92   loopfiles(toys.optargs, do_cat);
93 }
94 
catv_main(void)95 void catv_main(void)
96 {
97   toys.optflags ^= FLAG_v;
98   loopfiles(toys.optargs, do_cat);
99 }
100