xref: /third_party/toybox/toys/posix/cat.c (revision 0f66f451)
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
7USE_CAT(NEWTOY(cat, "uvte", TOYFLAG_BIN))
8
9config CAT
10  bool "cat"
11  default y
12  help
13    usage: cat [-etuv] [FILE...]
14
15    Copy (concatenate) files to stdout.  If no files listed, copy from stdin.
16    Filename "-" is a synonym for stdin.
17
18    -e	Mark each newline with $
19    -t	Show tabs as ^I
20    -u	Copy one byte at a time (slow)
21    -v	Display nonprinting characters as escape sequences with M-x for
22    	high ascii characters (>127), and ^x for other nonprinting chars
23*/
24
25#define FOR_cat
26#define FORCE_FLAGS
27#include "toys.h"
28
29static void do_cat(int fd, char *name)
30{
31  int i, len, size = FLAG(u) ? 1 : sizeof(toybuf);
32
33  for(;;) {
34    len = read(fd, toybuf, size);
35    if (len<0) perror_msg_raw(name);
36    if (len<1) break;
37    if (toys.optflags&~FLAG_u) {
38      for (i = 0; i<len; i++) {
39        char c = toybuf[i];
40
41        if (c>126 && FLAG(v)) {
42          if (c>127) {
43            printf("M-");
44            c -= 128;
45          }
46          if (c == 127) {
47            printf("^?");
48            continue;
49          }
50        }
51        if (c<32) {
52          if (c == 10) {
53            if (FLAG(e)) xputc('$');
54          } else if (toys.optflags & (c==9 ? FLAG_t : FLAG_v)) {
55            printf("^%c", c+'@');
56            continue;
57          }
58        }
59        xputc(c);
60      }
61    } else xwrite(1, toybuf, len);
62  }
63}
64
65void cat_main(void)
66{
67  loopfiles(toys.optargs, do_cat);
68}
69