Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get the contents of a file at build time into my C++ string?

I have a file I am compiling in C++ in which I wish to have a string whose value is the contents of a file at the time of compilation.

In other words, I'd like to #include the file but have that be inside double quotes.

How can I do this in C++?

Now what if that file contains double quotes as part of its text, how do I get those escaped?

like image 785
WilliamKF Avatar asked Dec 22 '22 03:12

WilliamKF


1 Answers

You can use xxd -i /tmp/your_file > /tmp/your_file_as_string.c

Which will define a string literal for you:

$ cat /tmp/your_file_as_string.c
unsigned char _tmp_inc[] = {
  0x2e, 0x2f, 0x42, 0x61, 0x74, 0x63, 0x68, 0x2f, 0x6e, 0x65, 0x78, 0x74,
  0x4f, 0x6f, 0x6c, 0x73, 0x2f, 0x73, 0x63, 0x68, 0x65, 0x6d, 0x61, 0x5f,
  ...
  0x74, 0x61, 0x6c, 0x69, 0x64, 0x61, 0x74, 0x6f, 0x72, 0x2e, 0x65, 0x63,
  0x0a
};
unsigned int _tmp_inc_len = 1513;

Now you can use that defined string.

like image 185
Stephen Avatar answered Feb 16 '23 01:02

Stephen