summary refs log tree commit diff
path: root/.bin/xx.c
blob: 867ef8e4bc1e2d0f8185b8110c7506ee6c33bbb3 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
#if 0
exec clang -Weverything -Wno-vla $@ -o $(dirname $0)/xx $0
#endif

#include <ctype.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

static bool zero(const uint8_t *buf, size_t len) {
    for (size_t i = 0; i < len; ++i)
        if (buf[i]) return false;
    return true;
}

enum {
    FLAG_ASCII = 1,
    FLAG_OFFSET = 2,
    FLAG_SKIP = 4,
};

int main(int argc, char **argv) {
    size_t cols = 16;
    size_t group = 8;
    uint8_t flags = FLAG_ASCII | FLAG_OFFSET;
    char *path = NULL;

    while (getopt(argc, argv, "ac:fg:hk") > 0) {
        if (optopt == 'a')
            flags ^= FLAG_ASCII;
        else if (optopt == 'c')
            cols = (size_t) strtol(optarg, NULL, 10);
        else if (optopt == 'f')
            flags ^= FLAG_OFFSET;
        else if (optopt == 'g')
            group = (size_t) strtol(optarg, NULL, 10);
        else if (optopt == 'k')
            flags ^= FLAG_SKIP;
        else {
            printf("usage: xx [-afk] [-c N] [-g N] [FILE]\n");
            return (optopt == 'h') ? EXIT_SUCCESS : EXIT_FAILURE;
        }
    }
    if (!cols) return EXIT_FAILURE;
    if (argc > optind)
        path = argv[optind];

    FILE *file = path ? fopen(path, "r") : stdin;
    if (!file) {
        perror(path);
        return EXIT_FAILURE;
    }

    uint8_t buf[cols];
    size_t offset = 0, len = 0, i;
    for (;;) {
        offset += len;
        len = fread(buf, 1, sizeof(buf), file);
        if (!len) break;

        if ((flags & FLAG_SKIP) && len == sizeof(buf)) {
            static bool skip = false;
            if (zero(buf, len)) {
                if (!skip) printf("*\n");
                skip = true;
                continue;
            }
            skip = false;
        }

        if (flags & FLAG_OFFSET)
            printf("%08zx:  ", offset);

        for (i = 0; i < len; ++i) {
            if (group && i && !(i % group)) printf(" ");
            printf("%02x ", buf[i]);
        }

        if (flags & FLAG_ASCII) {
            for (i = len; i < cols; ++i)
                printf((group && !(i % group)) ? "    " : "   ");
            printf(" ");
            for (i = 0; i < len; ++i)
                printf("%c", isprint(buf[i]) ? buf[i] : '.');
        }

        printf("\n");
        if (len < sizeof(buf)) break;
    }

    if (ferror(file)) {
        perror(path);
        return EXIT_FAILURE;
    }
    return EXIT_SUCCESS;
}