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
|
#include <stdio.h>
#include <string>
using namespace std;
int main(int argc, char **argv)
{
if (argc != 4) {
fprintf(stderr, "Usage: bin2h INFILE BASENAME OUTFILE\n");
return 1;
}
string basename = argv[2];
for (char &ch : basename) {
if (!isalpha(ch) && !isdigit(ch)) {
ch = '_';
}
}
FILE *infp = fopen(argv[1], "rb");
if (infp == nullptr) {
perror(argv[1]);
abort();
}
FILE *outfp = fopen(argv[3], "w");
if (outfp == nullptr) {
perror(argv[3]);
abort();
}
fprintf(outfp, "// Generated by bin2h.cpp from %s. Do not edit by hand.\n", argv[1]);
fprintf(outfp, "#include <stddef.h>\n");
fprintf(outfp, "unsigned char _binary_%s[] = {", basename.c_str());
size_t num_bytes = 0;
while (!feof(infp)) {
if (num_bytes++ % 16 == 0) {
fprintf(outfp, "\n\t");
}
int ch = getc(infp);
if (ch == -1) {
break;
}
fprintf(outfp, "0x%02x, ", ch);
}
fprintf(outfp, "\n};\n");
fprintf(outfp, "unsigned char *_binary_%s_data = _binary_%s;\n", basename.c_str(), basename.c_str());
fprintf(outfp, "size_t _binary_%s_size = sizeof(_binary_%s);\n", basename.c_str(), basename.c_str());
return 0;
}
|