summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorLouis Burda <quent.burda@gmail.com>2024-01-09 17:41:12 +0100
committerLouis Burda <quent.burda@gmail.com>2024-01-09 17:41:17 +0100
commit1692d28a6efe504594f2b275b28db096e51168a3 (patch)
treee74ada346474ee22b38062fdd12d284f8c0bb54d
parent67be03067c8553cda074386c4c2f14d8e525be23 (diff)
downloadhex-1692d28a6efe504594f2b275b28db096e51168a3.tar.gz
hex-1692d28a6efe504594f2b275b28db096e51168a3.zip
Add newline aware output flag
-rw-r--r--hexv.c54
1 files changed, 38 insertions, 16 deletions
diff --git a/hexv.c b/hexv.c
index ffde5f2..2e93a0f 100644
--- 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);
}
}
+