new: tool that turns a file into a valid C string

This commit is contained in:
2025-07-18 10:52:00 -04:00
parent 17e0cd44aa
commit 532a1273d8
4 changed files with 86 additions and 8 deletions

42
tools/file_to_string.py Executable file
View File

@@ -0,0 +1,42 @@
#!/usr/bin/env python3
import argparse
def c_escape_byte(b):
if b == 0x09:
return r'\t'
elif b == 0x0A:
return r'\n'
elif b == 0x0D:
return r'\r'
elif b == 0x5C: # \
return r'\\'
elif b == 0x22: # "
return r'\"'
elif 0x20 <= b <= 0x7E:
return chr(b)
elif b == 0x25: # %
return '%%'
else:
return f'\\x{b:02x}'
def file_to_c_string(filepath):
with open(filepath, 'rb') as f:
content = f.read()
escaped = ''.join(c_escape_byte(b) for b in content)
return f'"{escaped}"'
def main():
parser = argparse.ArgumentParser(
description='Convert file contents to a valid C string literal.')
parser.add_argument('input', help='Path to input file')
args = parser.parse_args()
c_string = file_to_c_string(args.input)
print(c_string)
if __name__ == '__main__':
main()