"#include" a text file in a C program as a char[]
I'd suggest using (unix util)xxd for this.you can use it like so
$ echo hello world > a$ xxd -i a
outputs:
unsigned char a[] = { 0x68, 0x65, 0x6c, 0x6c, 0x6f, 0x20, 0x77, 0x6f, 0x72, 0x6c, 0x64, 0x0a};unsigned int a_len = 12;
The question was about C but in case someone tries to do it with C++11 then it can be done with only little changes to the included text file thanks to the new raw string literals:
In C++ do this:
const char *s =#include "test.txt";
In the text file do this:
R"(Line 1Line 2Line 3Line 4Line 5Line 6)"
So there must only be a prefix at the top of the file and a suffix at the end of it. Between it you can do what you want, no special escaping is necessary as long as you don't need the character sequence )"
. But even this can work if you specify your own custom delimiter:
R"=====(Line 1Line 2Line 3Now you can use "( and )" in the text file, too.Line 5Line 6)====="
You have two possibilities:
- Make use of compiler/linker extensions to convert a file into a binary file, with proper symbols pointing to the begin and end of the binary data. See this answer: Include binary file with GNU ld linker script.
- Convert your file into a sequence of character constants that can initialize an array. Note you can't just do "" and span multiple lines. You would need a line continuation character (
\
), escape"
characters and others to make that work. Easier to just write a little program to convert the bytes into a sequence like'\xFF', '\xAB', ...., '\0'
(or use the unix toolxxd
described by another answer, if you have it available!):
Code:
#include <stdio.h>int main() { int c; while((c = fgetc(stdin)) != EOF) { printf("'\\x%X',", (unsigned)c); } printf("'\\0'"); // put terminating zero}
(not tested). Then do:
char my_file[] = {#include "data.h"};
Where data.h is generated by
cat file.bin | ./bin2c > data.h