-
Notifications
You must be signed in to change notification settings - Fork 0
/
bin2c.c
113 lines (89 loc) · 1.59 KB
/
bin2c.c
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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
#include <stdio.h>
int main(int argc, char** argv)
{
if (argc < 4)
return 1;
const char* sym = argv[1];
FILE* in = NULL;
FILE* out = NULL;
in = fopen(argv[2], "r");
if (!in)
{
perror("opening input file failed");
goto fail;
}
out = fopen(argv[3], "wt");
if (!out)
{
perror("opening input file failed");
goto fail;
}
if (fprintf(out, "#include <stddef.h>\n") < 0)
{
perror("write failed");
goto fail;
}
if (fprintf(out, "const char %s[] = {\n", sym) < 0)
{
perror("write failed");
goto fail;
}
unsigned char buf[4096];
size_t total_size = 0;
size_t bytes_read;
while ((bytes_read = fread(buf, 1, sizeof buf, in)) > 0)
{
size_t i = 0;
for (; i + 8 < bytes_read; i += 8)
{
int written = fprintf(out,
"0x%02x, 0x%02x, 0x%02x, 0x%02x, "
"0x%02x, 0x%02x, 0x%02x, 0x%02x, \n",
buf[i], buf[i+1], buf[i+2], buf[i+3],
buf[i+4], buf[i+5], buf[i+6], buf[i+7]
);
if (written < 0)
{
perror("write failed");
goto fail;
}
}
for (; i < bytes_read; ++i)
{
int written = fprintf(out, "0x%02x, ", buf[i]);
if (written < 0)
{
perror("write failed");
goto fail;
}
}
if (fputc('\n', out) == EOF)
{
perror("write failed");
goto fail;
}
total_size += bytes_read;
}
if (ferror(in))
{
perror("read failed");
goto fail;
}
if (fprintf(out, "};\n") < 0)
{
perror("write failed");
goto fail;
}
if (fprintf(out, "size_t %s_size = %zu;\n\n", sym, total_size) < 0)
{
perror("write failed");
goto fail;
}
return 0;
fail:
if (in)
fclose(in);
if (out)
fclose(out);
return 1;
}