Skip to content

Instantly share code, notes, and snippets.

@sryze
Last active January 4, 2019 03:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sryze/c64c47397cd3e60c16d6d73598df1adb to your computer and use it in GitHub Desktop.
Save sryze/c64c47397cd3e60c16d6d73598df1adb to your computer and use it in GitHub Desktop.
Generate C code from a file
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char **argv)
{
FILE *file;
FILE *out_file;
unsigned char c;
int i;
if (argc < 3) {
fprintf(stderr, "Usage: cdump file var_name [out_file]\n");
return EXIT_FAILURE;
}
if (argc >= 4) {
out_file = fopen(argv[3], "w");
if (out_file == NULL) {
fprintf(stderr, "Could not open output file: %s\n", strerror(errno));
return EXIT_FAILURE;
}
} else {
out_file = stdout;
}
file = fopen(argv[1], "rb");
if (file == NULL) {
fprintf(stderr, "Could not open input file: %s\n", strerror(errno));
return EXIT_FAILURE;
}
fprintf(out_file,
"/* This file was automatically generated by cdump. DO NOT EDIT. */\n\n");
fprintf(out_file, "static const char %s[] = {\n", argv[2]);
i = 0;
while ((fread(&c, sizeof(c), 1, file)) != 0) {
if (i == 0) {
fprintf(out_file, "\t\"");
}
if (c >= 32 && c <= 126) {
if (c == '"') {
fputs("\\\"", out_file);
i += 2;
} else if (c == '\\') {
fputs("\\\\", out_file);
i += 2;
} else {
putc(c, out_file);
i += 1;
}
} else {
fprintf(out_file, "\\x%02x", c);
i += 4;
}
if (i >= 68) {
fputs("\"\n", out_file);
i = 0;
}
}
if (i != 0) {
fputs("\"\n", out_file);
}
fprintf(out_file, "\n};\n");
return EXIT_SUCCESS;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment