将文本文件嵌入本机 Windows 应用程序的资源中
我有一个 C++ Windows 程序。我有一个包含一些数据的文本文件。目前,文本文件是一个单独的文件,它在运行时加载并解析。如何将其作为资源嵌入到二进制文件中?
I have a C++ Windows program. I have a text file that has some data. Currently, the text file is a separate file, and it is loaded at runtime and parsed. How is it possible to embed this into the binary as a resource?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
由于您正在开发本机 Windows 应用程序,因此您想要做的是创建用户定义的资源以将文本文件的内容嵌入到编译的资源中。
用户定义资源的格式MSDN 上有记录,以下函数加载它。
您可以将文本文件嵌入到资源文件中,如下所示:
其中
nameID
是一些唯一的 16 位无符号整数,用于标识资源,typeID
是一些唯一的 16 位无符号整数大于 255 标识资源类型(您可以在resource.h
文件中定义这些整数)。filename
是要将其二进制内容嵌入到编译资源中的文件的路径。所以你可能会这样:
在
resource.h
中:在你的资源文件中:
然后你像这样加载它(为了清楚起见,省略了错误检查代码):
请注意,你实际上不必释放资源,因为资源驻留在可执行文件的二进制文件中,当程序退出时系统会自动删除它们(函数
FreeResource()
在 32 位和 64 位 Windows 系统上不执行任何操作) 。由于数据驻留在可执行二进制文件中,因此您无法直接通过检索到的指针修改它(这就是为什么
LoadFileInResource()
函数实现将指针存储在const char*
)。您需要使用BeginUpdateResource()
、UpdateResource()
和EndUpdateResource()
函数来执行此操作。Since you're working on a native Windows application, what you want to do is to create a user-defined resource to embed the contents of the text file into the compiled resource.
The format of a user-defined resource is documented on MSDN, as are the functions for loading it.
You embed your text file in a resource file like this:
where
nameID
is some unique 16-bit unsigned integer that identifies the resource andtypeID
is some unique 16-bit unsigned integer greater than 255 that identifies the resource type (you may define those integers in theresource.h
file).filename
is the path to the file that you want to embed its binary contents into the compiled resource.So you might have it like this:
In
resource.h
:In your resource file:
Then you load it like this (error-checking code omitted for clarity):
Note that you don't actually have to free the resource since the resource resides in the binary of the executable and the system will delete them automatically when the program exits (the function
FreeResource()
does nothing on 32-bit and 64-bit Windows systems).Because the data resides in the executable binary, you can't modify it via the retrieved pointer directly (that's why the
LoadFileInResource()
function implementation stores the pointer in aconst char*
). You need to use theBeginUpdateResource()
,UpdateResource()
, andEndUpdateResource()
functions to do that.您可以使用 xxd(从 Linux 计算机或可能是 cygwin)生成 .h/.cc 文件的数据。
有很多堆栈溢出问题对此进行了详细扩展:
You can use
xxd
(from a linux machine or probably cygwin) to generate the data for a .h/.cc file.There are lots of stack overflow questions that expand on this in detail: