blob: f8229c20e47798bac7f4e213f5d32165ee995d06 [file] [log] [blame]
Rob Landley8abbee42006-05-31 19:36:04 +00001/* 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 "busybox.h"
Rob Landley8abbee42006-05-31 19:36:04 +000014
15int catv_main(int argc, char **argv)
16{
Bernhard Reutner-Fischer73561cc2006-08-28 23:31:54 +000017 int retval = EXIT_SUCCESS, fd;
18 unsigned long flags;
Rob Landley8abbee42006-05-31 19:36:04 +000019
20 flags = bb_getopt_ulflags(argc, argv, "etv");
Bernhard Reutner-Fischer73561cc2006-08-28 23:31:54 +000021#define CATV_OPT_e (1<<0)
22#define CATV_OPT_t (1<<1)
23#define CATV_OPT_v (1<<2)
24 flags ^= CATV_OPT_v;
Rob Landley8abbee42006-05-31 19:36:04 +000025
26 argv += optind;
27 do {
Bernhard Reutner-Fischer73561cc2006-08-28 23:31:54 +000028 /* Read from stdin if there's nothing else to do. */
Rob Landley8abbee42006-05-31 19:36:04 +000029 fd = 0;
Bernhard Reutner-Fischer73561cc2006-08-28 23:31:54 +000030 if (*argv && 0 > (fd = xopen(*argv, O_RDONLY)))
31 retval = EXIT_FAILURE;
32 else for (;;) {
Rob Landley8abbee42006-05-31 19:36:04 +000033 int i, res;
34
35 res = read(fd, bb_common_bufsiz1, sizeof(bb_common_bufsiz1));
Bernhard Reutner-Fischer73561cc2006-08-28 23:31:54 +000036 if (res < 0)
37 retval = EXIT_FAILURE;
38 if (res < 1)
39 break;
40 for (i = 0; i < res; i++) {
41 char c = bb_common_bufsiz1[i];
Rob Landley8abbee42006-05-31 19:36:04 +000042
Bernhard Reutner-Fischer73561cc2006-08-28 23:31:54 +000043 if (c > 126 && (flags & CATV_OPT_v)) {
Rob Landley8abbee42006-05-31 19:36:04 +000044 if (c == 127) {
Bernhard Reutner-Fischer73561cc2006-08-28 23:31:54 +000045 bb_printf("^?");
Rob Landley8abbee42006-05-31 19:36:04 +000046 continue;
47 } else {
Bernhard Reutner-Fischer73561cc2006-08-28 23:31:54 +000048 bb_printf("M-");
Rob Landley8abbee42006-05-31 19:36:04 +000049 c -= 128;
50 }
51 }
52 if (c < 32) {
53 if (c == 10) {
Bernhard Reutner-Fischer73561cc2006-08-28 23:31:54 +000054 if (flags & CATV_OPT_e)
55 putchar('$');
56 } else if (flags & (c==9 ? CATV_OPT_t : CATV_OPT_v)) {
57 bb_printf("^%c", c+'@');
Rob Landley8abbee42006-05-31 19:36:04 +000058 continue;
59 }
60 }
61 putchar(c);
62 }
63 }
Bernhard Reutner-Fischer73561cc2006-08-28 23:31:54 +000064 if (ENABLE_FEATURE_CLEAN_UP && fd)
65 close(fd);
Rob Landley8abbee42006-05-31 19:36:04 +000066 } while (*++argv);
67
68 return retval;
69}