Skip to content

Instantly share code, notes, and snippets.

@hypernewbie
Created May 19, 2015 18:40
Show Gist options
  • Save hypernewbie/dfbb46b3359531d30a3f to your computer and use it in GitHub Desktop.
Save hypernewbie/dfbb46b3359531d30a3f to your computer and use it in GitHub Desktop.
#include <cstdio>
#include <cstdlib>
#include <cassert>
#include <string>
#include <algorithm>
using namespace std;
size_t GetFileSize(FILE * fp)
{
// Should implement this in a slightly more conformant way.
assert(fp);
fseeko(fp, 0, SEEK_END);
off_t sz = ftello(fp);
assert(sz != -1);
rewind(fp);
return (size_t) sz;
}
void AppendBuffer(string& out, const char* buffer, size_t sz, string filename)
{
replace( filename.begin(), filename.end(), '.', '_');
replace( filename.begin(), filename.end(), '/', '_');
replace( filename.begin(), filename.end(), '\\', '_');
char temp[128];
out += "static unsigned int ";
out += filename;
out += "_size = ";
snprintf(temp, 128, "%ld", sz);
out += temp;
out += ";\n";
out += "static unsigned char ";
out += filename;
out += "[] = {";
for (size_t i = 0; i < sz; i++) {
if (i % 25 == 0) {
out += "\n ";
}
snprintf(temp, 128, "0x%.2x%s", (int) ((unsigned char) buffer[i]), (i+1 == sz) ? "" : ", ");
out += temp;
}
out += "\n};\n\n";
}
int main(int argc, char* argv[]) {
string out;
for (int i = 1; i < argc; i++) {
fprintf(stderr, "Processing %s\n", argv[i]);
FILE * fp = fopen(argv[i], "rb");
assert(fp);
size_t sz = GetFileSize(fp);
char* buffer = new char[sz];
size_t r = fread(buffer, 1, sz, fp);
assert(r == sz);
AppendBuffer(out, buffer, sz, argv[i]);
delete[] buffer;
}
printf("%s", out.c_str());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment