3 // convert a binary file into a C source vector
5 // put into the public domain by Sandro Sigala
7 // syntax: bin2c [-c] [-z] <input_file> <output_file>
9 // -c add the "const" keyword to definition
10 // -z terminate the array with a zero (useful for embedded C strings)
13 // bin2c -c myimage.png myimage_png.cpp
14 // bin2c -z sometext.txt sometext_txt.cpp
26 int zeroterminated
= 0;
31 if (c
== EOF
&& zeroterminated
) {
39 void process(const char *ifname
, const char *ofname
)
47 if ((cp3
= strrchr(ofname
, '/')) != NULL
)
50 if ((cp3
= strrchr(ofname
, '\\')) != NULL
)
57 cp2
= strrchr(buf2
, '.');
65 ifile
= fopen(ifname
, "rb");
67 fprintf(stderr
, "cannot open %s for reading\n", ifname
);
70 ofile
= fopen(ofname
, "wb");
72 fprintf(stderr
, "cannot open %s for writing\n", ofname
);
75 char buf
[PATH_MAX
], *p
;
77 if ((cp
= strrchr(ifname
, '/')) != NULL
)
80 if ((cp
= strrchr(ifname
, '\\')) != NULL
)
86 for (p
= buf
; *p
!= '\0'; ++p
)
89 fprintf(ofile
,"#include \"%s\" \n\n",buf2
);
90 fprintf(ofile
, "%sunsigned char %s[] = {\n", useconst
? "const " : "", buf
);
92 while ((c
= myfgetc(ifile
)) != EOF
) {
98 fprintf(ofile
, "0x%.2x, ", c
);
102 fprintf(ofile
, "\n};\n");
105 fprintf(ofile
,"int %s_length = %i; \n",buf
,counter
);
109 o2file
= fopen(buf2
, "wb");
110 if (o2file
== NULL
) {
111 fprintf(stderr
, "cannot open %s for writing\n", buf2
);
115 fprintf(o2file
, "#ifndef __%s__ \n", buf
);
116 fprintf(o2file
, "#define __%s__ \n", buf
);
118 fprintf(o2file
, "extern %sunsigned char %s[]; \n\n", useconst
? "const " : "", buf
);
119 fprintf(o2file
, "extern int %s_length; \n\n", buf
);
121 fprintf(o2file
, "#endif \n");
130 fprintf(stderr
, "usage: bin2c <input_files> \n");
134 int main(int argc
, char **argv
)
140 for(i
= 1;i
< argc
; i
++)
144 strcpy(buf
, argv
[i
]);
145 cp
= strrchr(buf
, '.');
148 process(argv
[i
], buf
);
154 if (!strcmp(argv[1], "-c")) {
158 } else if (!strcmp(argv[1], "-z")) {
169 process(argv[1], argv[2]);