2014-03-03 32 views
3

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

是无论如何它可能有包含到项目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)); 

阅读,但我怎么看单独的行?不知何故,我无法阅读单独的行。我似乎无法区分一条线与另一条线。

+5

我认为'资源''.rc'文件做你正在寻找。这就是我将图像和图标打包成Visual C++程序的方式。 http://msdn.microsoft.com/en-us/library/7zxb70x7.aspx – zero298

+2

这似乎涵盖了几乎所有内容:http://stackoverflow.com/questions/7366391/embedding-a-text-file-in-an -exe-which-can-be-accessible-using-fopen – Eejin

+0

@Eejin为了让它形成一个字符串文字,很多陷阱只是包括纯文本文件。文本中包含特殊字符怎么办? –

回答

0

我只能给你一个解决办法,如果你不想担心文件的路径,你可以: - 增加你的文件到您的项目 - 增加一个岗位建设活动,以复制您的数据.txt文件在您的生成文件夹中。

0

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

0

你可以把的std :: string变量的文件的内容:

std::string data_txt = ""; 

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

一两件事 - 你需要使用\字符每一个前处理特殊字符,如“'

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字符串。

+0

为什么所有的分号:D –

相关问题