commit 1692d28a6efe504594f2b275b28db096e51168a3
parent 67be03067c8553cda074386c4c2f14d8e525be23
Author: Louis Burda <quent.burda@gmail.com>
Date: Tue, 9 Jan 2024 17:41:12 +0100
Add newline aware output flag
Diffstat:
M | hexv.c | | | 54 | ++++++++++++++++++++++++++++++++++++++---------------- |
1 file changed, 38 insertions(+), 16 deletions(-)
diff --git a/hexv.c b/hexv.c
@@ -1,8 +1,13 @@
+#include <fcntl.h>
+#include <unistd.h>
+#include <err.h>
+#include <errno.h>
+
#include <stdlib.h>
+#include <string.h>
#include <stdio.h>
#include <stdint.h>
-#include <fcntl.h>
-#include <unistd.h>
+#include <stdbool.h>
static const char hex[] = "0123456789abcdef";
@@ -20,6 +25,9 @@ static int gradient[256] = {
[255] = 255,
};
+/* command-line arguments */
+static bool newline_aware = false;
+
void
colorhex(uint8_t c)
{
@@ -69,39 +77,52 @@ printrow(char *row, size_t pos, size_t len)
void
tohex(int fd)
{
- size_t pos, i, k;
+ size_t last, pos, i, k;
ssize_t nread;
char buf[4096];
char row[16];
- pos = 0;
+ last = pos = 0;
while (1) {
nread = read(fd, buf, sizeof(buf));
if (nread <= 0) break;
for (i = 0; i < nread; i++, pos++) {
- row[pos % 16] = buf[i];
- if ((pos + 1) % 16 == 0)
- printrow(row, pos & ~15UL, 16);
+ row[pos - last] = buf[i];
+ if (pos == last + 15 || buf[i] == '\n' && newline_aware) {
+ printrow(row, last, pos - last + 1);
+ last = pos + 1;
+ }
}
}
- if (pos % 16 != 0)
- printrow(row, pos & ~15UL, pos % 16);
+ if (pos != last)
+ printrow(row, last, pos - last);
}
int
main(int argc, const char **argv)
{
- int i, fd;
+ const char **arg, **farg;
+ int fd;
- if (argc > 1) {
- for (i = 1; i < argc; i++) {
- if (i > 1) printf("\n");
- fd = open(argv[i], O_RDONLY);
+ if (argc < 1) return 1;
+
+ for (arg = argv + 1; *arg; arg++) {
+ if (!strcmp(*arg, "-n") || !strcmp(*arg, "--newline-aware")) {
+ newline_aware = true;
+ } else {
+ break;
+ }
+ }
+
+ if (*arg) {
+ for (farg = arg; *farg; farg++) {
+ if (farg != arg) printf("\n");
+ fd = open(*farg, O_RDONLY);
if (fd < 0) {
- fprintf(stderr, "Could not open file: %s\n",
- argv[i]);
+ fprintf(stderr, "hexv: open '%s': %s",
+ *farg, strerror(errno));
continue;
}
tohex(fd);
@@ -111,3 +132,4 @@ main(int argc, const char **argv)
tohex(0);
}
}
+