summary refs log tree commit diff
path: root/.bin/xx.c
blob: 153ba74e656e7f66f472c6024df60b5bbafa602f (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
#if 0
exec cc -Weverything -Wno-vla -o ~/.bin/xx $0
#endif

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

int main(int argc, char **argv)
{
    size_t cols = 16;
    char *path = NULL;

    while (getopt(argc, argv, "c:") > 0)
        if (optopt == 'c') {
            cols = (size_t) strtol(optarg, NULL, 10);
            if (!cols) return EXIT_FAILURE;
        } else 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];
    for (;;) {
        size_t n = fread(buf, 1, sizeof(buf), file);
        for (size_t i = 0; i < n; ++i)
            printf("%02x ", buf[i]);
        printf("\n");
        if (n < sizeof(buf)) break;
    }
    if (ferror(file)) {
        perror(path);
        return EXIT_FAILURE;
    }

    return EXIT_SUCCESS;
}