Search code examples
cstringbuildbuild-process

Does anything exist that converts text files into string literals as a build step?


I have multiple text files, and I'd like them to be converted into source files containing string literals at build time.

For example, if hello.txt contains this text:

Hello,

This is a text file.

I'm looking for the output to be something like this:

const char* HELLO_TXT = "Hello,\n\nThis is a text file.";

Does anything like this already exist, or do I have to roll my own?


Solution

  • There's a standard utility called xxd which will do exactly this (http://linux.die.net/man/1/xxd ). Add it as as one of your build steps before compiling. The -i option generates a hex dump of a file in "C include" format. So with a hello.txt thta contains only the string "hello", the output of

    xxd -i hello.txt > hello.h
    

    would look something like:

    char *hello_txt = { 0x68, 0x65, 0x6c, 0x6c, 0x6f };
    int hello_txt_len = 5;
    

    You can then #include this file into your source code and access hello_txt to get the contents of your file. Note that the array is not null terminated.