动态地在C可执行文件中包含文本

对C和编译语言来说非常新。 我需要在此代码中基本上包含来自另一个文件的一行动态文本:

#if T2T_NDEFFILE_PREDEF == URI const uint8_t T2T_DATA_DEF[] = { #include "/home/link" // Terminator TLV 0xF3 }; #endif 

我已经尝试使用#include链接到文本文件,但是当文件“链接”中的文本发生更改时,它显然不会在编译的可执行文件中更改。 有没有简单的方法来做到这一点?

#include指令只是将另一个文件的内容复制到源代码中,然后由C编译器转换为可执行文件。 换句话说,它是一次性过程,其他文件“烘焙”到您的代码中。

如果您需要在每次运行程序时“动态”重新加载文件的内容,则需要使用C代码自行加载。 这是一个例子,来自我自己的一个项目:

 /* [PUBLIC] Load the contents of a file into a malloc()'d buffer. */ unsigned char *txtLoadFile(const char *file_name, long *length) { FILE *fsrc = NULL; unsigned char *data = NULL; long size = 0; /* Attempt to open the requested file. */ fsrc = fopen(file_name, "rb"); if (!fsrc) { return NULL; } /* Get the length of the file in bytes. */ fseek(fsrc, 0, SEEK_END); size = (long)ftell(fsrc); rewind(fsrc); /* Copy the data into memory (with an extra zero byte, in case it's text). */ data = (unsigned char*)malloc(size + 1); if (data) { memset(data, 0, size + 1); fread(data, 1, size, fsrc); } fclose(fsrc); /* Return the result. */ if (length) { *length = size; } return data; } 

这段代码应该在很大程度上不言自明,但有一些事情值得指出:

  • 该文件以rb (读取二进制)模式打开 – 您可能需要使用r (读取文本),具体取决于您正在执行的操作。 如果是这样,你可能想要使用普通的char*而不是unsigned char *存储数据,就像我在这里所做的那样。
  • 为字符串的零NULL终结符字符分配一个额外的字节。
  • 缓冲区存储在动态分配的内存中。 由于您似乎更熟悉Python或Ruby等动态语言,我应该提醒您,一旦完成它就需要free()分配的内存。