将数据文件包含到C++项目中

Including data file into C++ project

本文关键字:C++ 项目 数据 文件包      更新时间:2023-10-16

我有一个数据文件data.txt,其中包括字符和数字数据。通常,我通过使用以下文件流读取程序中的data.txtCCD_ 1然后使用CCD_ 2来读取这些值。

是否可以将data.txt文件包含在项目中并编译它与项目,这样当我阅读文件时,我就不必担心路径(我的意思是,我只是使用了一些类似ifstreaminfile("data.txt",ios::in) ).的东西

此外,如果我能用我的项目编译文件,我就不必担心提供一个单独的data.txt文件和我的发布版本给任何其他想要使用我的程序。

我不想将data.txt文件更改为某种头文件。我想保持
.txt文件的原样,并以某种方式将其打包到我正在构建的可执行文件中。我仍然希望继续使用ifstream infile("data.txt",ios::in)并读取文件
中的行,但希望data.txt文件与其他.h或.cpp文件一样与项目在一起。

我正在使用C++visual studio 2010。这将是一个对我试图做的上述事情提供一些见解的人do.

更新

我设法使用下面的代码作为资源读取数据文件

HRSRC hRes = FindResource(GetModuleHandle(NULL), MAKEINTRESOURCE(IDR_TEXT1), _T("TEXT")); 
DWORD dwSize = SizeofResource(GetModuleHandle(NULL), hRes); HGLOBAL hGlob = LoadResource(GetModuleHandle(NULL), hRes); 
const BYTE* pData = reinterpret_cast<const BYTE*>(::LockResource(hGlob)); 

但是我该如何阅读单独的行呢?不知怎么的,我读不懂那几行。我似乎无法区分一行和另一行。

我可以给你一个解决方法,如果你不想担心文件的路径,你可以:-将文件添加到项目中-添加一个构建后事件,将data.txt文件复制到构建文件夹中。

还有一个类似的问题,也需要在C++代码中包含外部文件。请在这里查看我的答案。另一种方法是在项目中包含自定义资源,然后使用FindResource、LoadResource、LockResource来访问它

您可以将文件的内容放在std::string variable:中

std::string data_txt = "";

然后使用STL中的sscanf或字符串流来解析内容。

还有一件事-你需要在每个字符之前使用\字符来处理像"这样的特殊字符。

对于任何类型的文件,基于RBerteig anwser,您可以使用python:做一些简单的事情

该程序将生成一个text.txt.c文件,该文件可以编译并链接到您的代码,将任何文本或二进制文件直接嵌入到您的exe中,并直接从变量中读取:

import struct;                  #    Needed to convert string to byte
f = open("text.txt","rb")       #    Open the file in read binary mode
s = "unsigned char text_txt_data[] = {"
b = f.read(1)                   #    Read one byte from the stream
db = struct.unpack("b",b)[0]     #    Transform it to byte
h = hex(db)                      #    Generate hexadecimal string
s = s + h;                      #    Add it to the final code
b = f.read(1)                   #    Read one byte from the stream
while b != "":
s = s + ","                 #    Add a coma to separate the array
db = struct.unpack("b",b)[0] #    Transform it to byte
h = hex(db)                  #    Generate hexadecimal string
s = s + h;                  #    Add it to the final code
b = f.read(1)               #    Read one byte from the stream
s = s + "};"                     #    Close the bracktes
f.close()                       #    Close the file
# Write the resultan code to a file that can be compiled
fw = open("text.txt.c","w");   
fw.write(s);
fw.close();

会产生类似的东西

unsigned char text_txt_data[] = {0x52,0x61,0x6e,0x64,0x6f,0x6d,0x20,0x6e,0x75...

之后,您可以在另一个c文件中使用您的数据,使用如下代码的变量:

extern unsigned char text_txt_data[];

现在我想不出两种方法可以把它转换成可读的文本。使用内存流或将其转换为c字符串。