如何在构建时将文件的内容放入我的C++字符串中?

Wil*_*mKF 4 c++ string include

我有一个我在C++中编译的文件,其中我希望有一个字符串,其值是编译时文件的内容.

换句话说,我想#include文件,但有双引号.

我怎么能用C++做到这一点?

现在如果该文件包含双引号作为其文本的一部分,如何将这些文件转义?

Ste*_*hen 5

您可以使用 xxd -i /tmp/your_file > /tmp/your_file_as_string.c

这将为您定义一个字符串文字:

$ 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;
Run Code Online (Sandbox Code Playgroud)

现在您可以使用该定义的字符串.

  • @WilliamKF:不幸的是,不是直接的.关于SO的答案提供了一种方法http://stackoverflow.com/questions/410980/include-a-text-file-in-ac-program-as-a-char (2认同)