将数据文件包含到C++项目中
Including data file into C++ project
我有一个数据文件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字符串。
- 使用C++库在Android项目中修改gradle中的cmake参数,用于插入指令的测试
- 无法在 CLion 中构建 C++ 项目
- 运行同一解决方案的另一个项目的项目
- CMake-按正确顺序将项目与C运行时对象文件链接
- 如何在选项卡视图Qt中设置一个新项目,并保存以前的项目
- 欧拉项目#8答案是大以获得有效答案
- 从链接列表c++中删除一个项目
- CMake项目Boost库错误:Boost/config/compiler/gcc.hpp:165:10:致命错误:cs
- 既然存在危险,为什么项目要使用-I include开关
- cmake在我的项目中所需的所有静态库都不成功
- QT通过C++添加映射QML项目
- 我的项目不会像"undefined reference to `grpc::g_core_codegen_interface'"那样使用未定义的引用错误进行编译
- 在linux上调试巨大的C++项目
- 在其他文件中创建类时在 c++ 项目中不起作用
- 使外部项目可用于find_package CMake
- 在子目录中使用target_sources()命令时用于单元测试(qtest)的项目结构
- 使用外部SDK工具链文件在VisualStudio上生成项目编译错误
- 如何维护资源管理器项目视图中当前可见的项目列表
- 错误-我无法在VS2019中打开新的Qt项目
- 你能检查一下为什么在这个代码中从链接列表中删除项目不起作用吗