ref: ea234b61b3258a71793584c729427da8264e9a2f
parent: 5788a6536a136a541c4987d97a8ef225275d2e9b
author: Sigrid Solveig Haflínudóttir <[email protected]>
date: Wed Jan 25 08:26:10 EST 2023
add -p ("pipe") option
--- a/README.md
+++ b/README.md
@@ -20,5 +20,6 @@
# Notes
- * hx will print data as soon as it is available (if used on pipes), without buffering.
- * it provides an option `-s` ("section") to print data read separating it into sections.
+ * hx will print data as soon as it is available (if used on pipes), without buffering
+ * option `-s` ("section") to print data read immediately, separating it into *sections*
+ * option `-p` ("pipe") to print hex on `stderr` and pipe incoming data as is on `stdout`
--- a/hx.c
+++ b/hx.c
@@ -25,7 +25,7 @@
Linesz = 87,
};
-static int section = 0;
+static int section = 0, pipeit = 0;
static unsigned char *buf;
static const char b2h[] = (
"000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f"
@@ -61,6 +61,8 @@
section = 0;
break;
}
+ if (pipeit > 0)
+ write(pipeit, buf, sz);
for (i = 0; i < sz; ) {
if (lineoff == 0) {
@@ -112,7 +114,7 @@
if (off >= (int)sizeof(s)-Linesz) {
writes:
for (wroff = 0; wroff < off; wroff += r) {
- if ((r = write(1, s+wroff, off-wroff)) < 0) {
+ if ((r = write(pipeit+1, s+wroff, off-wroff)) < 0) {
sz = -1;
break;
}
@@ -149,7 +151,7 @@
goto ascii;
}
for (wroff = 0; wroff < off; wroff += r) {
- if ((r = write(1, s+wroff, off-wroff)) < 0) {
+ if ((r = write(pipeit+1, s+wroff, off-wroff)) < 0) {
sz = -1;
break;
}
@@ -157,7 +159,7 @@
}
if (section) {
- write(1, "\n", 1);
+ write(pipeit+1, "\n", 1);
goto again;
}
@@ -171,7 +173,7 @@
#endif
main(int argc, char **argv)
{
- int i, fd, res;
+ int i, fd, res, opts;
if ((buf = malloc(Bufsz)) == nil) {
perror("buf");
@@ -179,26 +181,38 @@
}
res = 0;
- if (argc > 1 && strcmp(argv[1], "-s") == 0) {
- section = 1;
- argv++;
- argc--;
- }
-
- if (argc == 1) {
- i = 1;
- fd = 0;
- goto dump;
- }
+ opts = 0;
for (i = 1; i < argc && res == 0; i++) {
+ if (argv[i][0] == '-' && argv[i][2] == 0) {
+ switch (argv[i][1]) {
+ case 's':
+ section = 1;
+ opts++;
+ break;
+ case 'p':
+ pipeit = 1;
+ opts++;
+ break;
+ default:
+ write(2, "unknown option: -", 17);
+ write(2, argv[i]+1, 1);
+ write(2, "\n", 1);
+ exits("usage");
+ }
+ if (opts == argc-1) {
+ fd = 0;
+ goto dump;
+ }
+ continue;
+ }
if ((fd = open(argv[i], OREAD)) < 0) {
perror(argv[i]);
res = 1;
} else {
- if (argc > 2) {
- write(1, "hx ", 3);
- write(1, argv[i], strlen(argv[i]));
- write(1, "\n", 1);
+ if (argc > 2+opts) {
+ write(pipeit+1, "hx ", 3);
+ write(pipeit+1, argv[i], strlen(argv[i]));
+ write(pipeit+1, "\n", 1);
}
dump:
if ((res = hx(fd)) != 0)