Bump to version 1.22.1
[platform/upstream/busybox.git] / coreutils / catv.c
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
10 /* See "Cat -v considered harmful" at
11  * http://cm.bell-labs.com/cm/cs/doc/84/kp.ps.gz */
12
13 //usage:#define catv_trivial_usage
14 //usage:       "[-etv] [FILE]..."
15 //usage:#define catv_full_usage "\n\n"
16 //usage:       "Display nonprinting characters as ^x or M-x\n"
17 //usage:     "\n        -e      End each line with $"
18 //usage:     "\n        -t      Show tabs as ^I"
19 //usage:     "\n        -v      Don't use ^x or M-x escapes"
20
21 #include "libbb.h"
22
23 int catv_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
24 int catv_main(int argc UNUSED_PARAM, char **argv)
25 {
26         int retval = EXIT_SUCCESS;
27         int fd;
28         unsigned opts;
29 #define CATV_OPT_e (1<<0)
30 #define CATV_OPT_t (1<<1)
31 #define CATV_OPT_v (1<<2)
32         typedef char BUG_const_mismatch[
33                 CATV_OPT_e == VISIBLE_ENDLINE && CATV_OPT_t == VISIBLE_SHOW_TABS
34                 ? 1 : -1
35         ];
36
37         opts = getopt32(argv, "etv");
38         argv += optind;
39 #if 0 /* These consts match, we can just pass "opts" to visible() */
40         if (opts & CATV_OPT_e)
41                 flags |= VISIBLE_ENDLINE;
42         if (opts & CATV_OPT_t)
43                 flags |= VISIBLE_SHOW_TABS;
44 #endif
45
46         /* Read from stdin if there's nothing else to do. */
47         if (!argv[0])
48                 *--argv = (char*)"-";
49         do {
50                 fd = open_or_warn_stdin(*argv);
51                 if (fd < 0) {
52                         retval = EXIT_FAILURE;
53                         continue;
54                 }
55                 for (;;) {
56                         int i, res;
57
58 #define read_buf bb_common_bufsiz1
59                         res = read(fd, read_buf, COMMON_BUFSIZE);
60                         if (res < 0)
61                                 retval = EXIT_FAILURE;
62                         if (res <= 0)
63                                 break;
64                         for (i = 0; i < res; i++) {
65                                 unsigned char c = read_buf[i];
66                                 if (opts & CATV_OPT_v) {
67                                         putchar(c);
68                                 } else {
69                                         char buf[sizeof("M-^c")];
70                                         visible(c, buf, opts);
71                                         fputs(buf, stdout);
72                                 }
73                         }
74                 }
75                 if (ENABLE_FEATURE_CLEAN_UP && fd)
76                         close(fd);
77         } while (*++argv);
78
79         fflush_stdout_and_exit(retval);
80 }