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

时间:2014-03-03 15:48:06

标签: c++ visual-studio-2010 text-files

我有一个数据文件data.txt,其中包含字符和数字数据。  通常我通过使用文件流来读取程序中的data.txt  ifstream infile("C:\\data.txt",ios::in);然后使用infile.getline来读取值。

无论如何都可以将data.txt文件包含在项目中并进行编译  它与项目,当我读取文件时,我不必担心路径  该文件(我的意思是我只使用ifstream infile("data.txt",ios::in) )

此外,如果我可以使用我的项目编译文件,我将不必担心  向我想要使用的任何其他人提供单独的data.txt文件和我的发布版本  我的节目。

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

我正在使用C ++ visual studio 2010。  如果有人能够对我正在努力的上述事情提供一些见解  做。

更新

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

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)); 

但是如何阅读单独的行?不知怎的,我无法阅读单独的行。我似乎无法将一行与另一行区分开来。

4 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

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

答案 2 :(得分:0)

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

std::string data_txt = "";

然后使用STL中的sscanf或stringstream来解析内容。

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

答案 3 :(得分:0)

对于任何类型的文件,基于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-string。