Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Download
7638 views
1
/* bin2hex.c -- Turn the contents of a file into an array of unsigned chars */
2
3
#include <stdio.h>
4
#include <string.h>
5
6
/* We never want to build memento versions of the cquote util */
7
#undef MEMENTO
8
9
static void
10
clean(char *p)
11
{
12
while (*p)
13
{
14
if ((*p == '/') || (*p == '.') || (*p == '\\') || (*p == '-'))
15
*p = '_';
16
p ++;
17
}
18
}
19
20
int
21
main(int argc, char **argv)
22
{
23
FILE *fi, *fo;
24
char name[256];
25
char *realname;
26
int i, j, c;
27
28
if (argc < 3)
29
{
30
fprintf(stderr, "usage: bin2hex output.h lots of text files\n");
31
return 1;
32
}
33
34
fo = fopen(argv[1], "wb");
35
if (!fo)
36
{
37
fprintf(stderr, "cquote: could not open output file '%s'\n", argv[1]);
38
return 1;
39
}
40
41
fprintf(fo, "/* This is an automatically generated file. Do not edit. */\n");
42
43
for (i = 2; i < argc; i++)
44
{
45
realname = strrchr(argv[i], '/');
46
if (!realname)
47
realname = strrchr(argv[i], '\\');
48
if (realname)
49
realname ++;
50
else
51
realname = argv[i];
52
53
if (strlen(realname) > (sizeof name - 1))
54
{
55
fprintf(stderr, "bin2hex: file name too long\n");
56
if (fclose(fo))
57
{
58
fprintf(stderr, "bin2hex: could not close output file '%s'\n", argv[1]);
59
return 1;
60
}
61
return 1;
62
}
63
64
strcpy(name, realname);
65
clean(name);
66
67
fi = fopen(argv[i], "rb");
68
69
j = 0;
70
while ((c = fgetc(fi)) != EOF)
71
{
72
if (j != 0)
73
{
74
fputc(',', fo);
75
fputc(j%8 == 0 ? '\n' : ' ', fo);
76
}
77
78
fprintf(fo, "0x%02x", c);
79
j++;
80
}
81
82
fputc('\n', fo);
83
84
if (fclose(fi))
85
{
86
fprintf(stderr, "bin2hex: could not close input file '%s'\n", argv[i]);
87
return 1;
88
}
89
90
}
91
92
if (fclose(fo))
93
{
94
fprintf(stderr, "bin2hex: could not close output file '%s'\n", argv[1]);
95
return 1;
96
}
97
98
return 0;
99
}
100
101