Skip to content

Instantly share code, notes, and snippets.

@PikalaxALT
Created November 27, 2019 15:50
Show Gist options
  • Save PikalaxALT/61a59e4369758172499c9e0d85998ce9 to your computer and use it in GitHub Desktop.
Save PikalaxALT/61a59e4369758172499c9e0d85998ce9 to your computer and use it in GitHub Desktop.
Simple utility to convert flat binary files into C objects
#include <stdio.h>
#include <ctype.h>
#include <string.h>
int main(int argc, char ** argv) {
static char label[BUFSIZ];
strcpy(label, "FILE_");
if (argc < 3) {
fprintf(stderr, "usage: %s INPUT OUTPUT\n"
"ERROR: insufficient arguments\n", argv[0]);
return 1;
}
FILE * infile = fopen(argv[1], "rb");
FILE * outfile = fopen(argv[2], "w");
if (!(infile && outfile)) {
if (infile) fclose(infile); else fprintf(stderr, "ERROR: unable to open file \"%s\" for reading\n", argv[1]);
if (outfile) fclose(outfile); else fprintf(stderr, "ERROR: unable to open file \"%s\" for writing\n", argv[2]);
return 1;
}
strcat(label, argv[1]);
for (int i = 0; label[i]; i++) {
if (!isalnum(label[i])) label[i] = '_';
}
fprintf(outfile, "const u8 %s[] = {", label);
unsigned char curr;
int i = 0;
while (!feof(infile)) {
if (i % 16 == 0) {
fputs("\n ", outfile);
}
fread(&curr, 1, 1, infile);
fprintf(outfile, "0x%02x%s", curr, feof(infile) ? "" : ",");
i++;
}
fputs("\n};\n", outfile);
fclose(outfile);
fclose(infile);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment