expr: small code shrink
[oweals/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 tarball for details.
8  */
9
10 /* See "Cat -v considered harmful" at
11  * http://cm.bell-labs.com/cm/cs/doc/84/kp.ps.gz */
12
13 #include "libbb.h"
14
15 int catv_main(int argc, char **argv);
16 int catv_main(int argc, char **argv)
17 {
18         int retval = EXIT_SUCCESS, fd;
19         unsigned flags;
20
21         flags = getopt32(argc, argv, "etv");
22 #define CATV_OPT_e (1<<0)
23 #define CATV_OPT_t (1<<1)
24 #define CATV_OPT_v (1<<2)
25         flags ^= CATV_OPT_v;
26         argv += optind;
27
28         /* Read from stdin if there's nothing else to do. */
29         fd = 0;
30         if (!argv[0])
31                 goto jump_in;
32         do {
33                 fd = open_or_warn(*argv, O_RDONLY);
34                 if (fd < 0) {
35                         retval = EXIT_FAILURE;
36                         continue;
37                 }
38  jump_in:
39                 for (;;) {
40                         int i, res;
41
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                                 char c = read_buf[i];
50
51                                 if (c > 126 && (flags & CATV_OPT_v)) {
52                                         if (c == 127) {
53                                                 printf("^?");
54                                                 continue;
55                                         }
56                                         printf("M-");
57                                         c -= 128;
58                                 }
59                                 if (c < 32) {
60                                         if (c == 10) {
61                                                 if (flags & CATV_OPT_e)
62                                                         putchar('$');
63                                         } else if (flags & (c==9 ? CATV_OPT_t : CATV_OPT_v)) {
64                                                 printf("^%c", c+'@');
65                                                 continue;
66                                         }
67                                 }
68                                 putchar(c);
69                         }
70                 }
71                 if (ENABLE_FEATURE_CLEAN_UP && fd)
72                         close(fd);
73         } while (*++argv);
74
75         fflush_stdout_and_exit(retval);
76 }