summaryrefslogtreecommitdiff
path: root/hexdump.c
blob: 5ad4452b2f92897bf3d075456d35ac0f915c009c (plain)
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
/* hexdump.c -- an "xxd -i" workalike */

#include <stdio.h>

int
hexdump(FILE *fo, FILE *fi)
{
    int c, n;

    n = 0;
    c = fgetc(fi);
    while (c != -1)
    {
	fprintf(fo, "0x%02x,", c);
	if (n % 16 == 15)
	    fprintf(fo, "\n");
	c = fgetc(fi);
	n ++;
    }

    return n;
}

int
main(int argc, char **argv)
{
    FILE *fo;
    FILE *fi;
    unsigned char name[256];
    unsigned char *p;
    int i, n, len;

    if (argc < 3)
    {
	fprintf(stderr, "usage: hexdump output.c input.dat\n");
	return 1;
    }

    fo = fopen(argv[1], "wb");
    if (!fo)
    {
	fprintf(stderr, "hexdump: could not open output file\n");
	return 1;
    }

    for (i = 2; i < argc; i++)
    {
	fi = fopen(argv[i], "rb");
	if (!fi)
	{
	    fprintf(stderr, "hexdump: could not open input file\n");
	    return 1;
	}

	strcpy(name, argv[i]);
	p = name;
	while (*p)
	{
	    if ((*p == '/') || (*p == '.') || (*p == '\\') || (*p == '-'))
		*p = '_';
	    p ++;
	}

	fprintf(fo, "const unsigned char %s[] = {\n", name);

	len = hexdump(fo, fi);

	fprintf(fo, "};\n");
	fprintf(fo, "const unsigned int %s_len = %d;\n", name, len);

	fclose(fi);
    }

    return 0;
}