Skip to content

Instantly share code, notes, and snippets.

@foxx
Created Nov 2, 2016
Embed
What would you like to do?
#!/usr/bin/env python
"""
Embed files into C arrays
Hacky solution because xxd didn't have enough features
"""
from __future__ import with_statement
from __future__ import print_function
import os
import sys
import re
import glob
def chunks(l, n):
"""Yield successive n-sized chunks from l."""
for i in xrange(0, len(l), n):
yield l[i:i + n]
def main(testdata_path, c_path, h_path):
print("Embedding testdata files into C")
os.path.isdir(testdata_path)
cout = ""
cout += "#include \"testdata.h\"\n"
cout += "#include <glib.h>\n\n"
hout = ""
hout += "#pragma once\n"
hout += "#include <glib.h>\n\n"
for path in glob.glob(testdata_path+'/*'):
if not os.path.isfile(path):
continue
print("Embedding %s" % path)
name = re.sub('[^a-zA-Z0-9]', '_', path)
# read file and build array
arr = []
with open(path, 'rb') as fh:
for c in fh.read():
nc = format(ord(c), "#04x");
arr.append(nc)
# output as chunks
filearr = "{\n"
for chunk in chunks(arr, 12):
filearr += " "
filearr += ", ".join(chunk)
filearr += ",\n"
filearr += " };"
# build c file
cout += "gchar *\n%s()\n{\n char out[%d] = %s\n" % (name, len(arr), filearr )
cout += " return g_strndup(out, sizeof(out));\n}\n\n"
# build h file
hout += "gchar *\n%s();\n\n" % (name)
# write C file
with open(c_path, "wb") as fh:
fh.write(cout)
# write H file
with open(h_path, "wb") as fh:
fh.write(hout)
print("Files generated OK")
if __name__ == '__main__':
import sys
if (len(sys.argv) != 4):
print("syntax: %s <testdata_path> <c_path> <h_path>" % sys.argv[0])
sys.exit(1)
main(*sys.argv[1:])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment