# hard-coding an entire text file into a C array

## Recommended Posts

BTownTKD    205
Hey guys - I'm working on a project in an embedded system, and we have a configuration file (in a text file, at the moment) that we'd like to hard-code into the program. It has many lines, quotation marks, and some special ascii characters, so copy/pasting inside a pair of quotation marks with a char* in front won't do it. I'd really like to avoid going through the entire text file, adding \n's and \"s any time I come across one. Is there some quick way to load the text file *directly* into the compilation, and have a char* point to it?

##### Share on other sites
Captain P    1092
Why not write a small script that does the hard work for you? Python, Perl, Ruby or whatever language you're familiar with, this would be a good place to put it to use.

##### Share on other sites
ToohrVyk    1595
No. I would possibly try something such as this:

int c, first = 1;printf("%s", "char data[] = {");while((c = getc()) != EOF)   printf("%s%d", first ? --first, "" : ",", c);printf("%s", "};");

##### Share on other sites
SiCrane    11839
Specifying your actual platform might be a good idea. Some environments do have the ability to directly embed files into executables. For example, on Windows platforms you can add any file type as a resource.

##### Share on other sites
BTownTKD    205
I'm currently working in Visual Studio 2005 (unfortunately using old-style C), but once this is working we plan on porting over to a custom IDE.

Just for my own curiosity, since I have not embedded resources into VS before; how do you point a char* at a Visual Studio resource, once it's been imported?

##### Share on other sites
SiCrane    11839
For an arbitrary resource type you can use LoadResource() and LockResource() to get a void * to the beginning of the resource in memory.

##### Share on other sites
Jaywalk    250
I trick I use for that situation is to use NASM to build the text file into an object which can be linked into the program.

Let's say that you want to have a C array called textfile which contains the file textfile.txt.

Have NASM assemble the following code into an ELF .o (or whatever object format you're using) which gets linked into your program
textfile:  incbin "textfile.txt"  DB 0

Congratulations, you now have the text file linked into your program as an ordinary C string. All you need to do is declare it in your code or a header file.
extern char textfile[];

##### Share on other sites
chairthrower    440
encode the file in base 64, then copy paste the output into your source file as a static string literal. To obtain the full text you just need to call char *p = unencode( p) variant. this obviates the (tricky) character escapsing that would be needed and is a generalised approach.