Skip to content

Instantly share code, notes, and snippets.

Created Nov 2, 2016
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")
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):
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
nc = format(ord(c), "#04x");
# 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:
# write H file
with open(h_path, "wb") as fh:
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])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment