I有一个数据文件data.txt,其中包括字符和数字数据。 通常我通过使用文件流中的文件流中读取data.txt
ifstream infile("C:\\data.txt",ios::in);
然后使用infile.getline
读取值。
无论如何,可以将数据包含在项目中并编译为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。 我想对上述事情提供一些见识是有点 做。
我设法使用以下代码将数据文件读取为资源
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文件。
Herey。 另一种方法是在您的项目中包含自定义资源,然后使用FindResource,LoadResource,LockResource访问它。
,基于Rberteig
anwser,您可以对Python进行简单的操作:
th这个程序将生成一个可以编译并链接到代码的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文件中使用您的数据:
externunsigned char text_txt_data [];
上面的python起作用,但是这种变化速度更快(在1MB文件上约为1000倍 - 避免了二次字符串构建):
#!/usr/bin/python3
import sys
f = open(sys.argv[1],"rb") # Open the file in read binary mode
s = "unsigned char text_txt_data[] = {\n"
b = f.read()
db = bytes(b)
l = 0
fw = open(sys.argv[2],"w")
fw.write(s);
for i in range(0, len(db)):
if l >= 16:
l = 0
#s = s + "\n"
fw.write(f"\n{hex(db[i])},")
else:
fw.write(f"{hex(db[i])},")
l = l + 1
fw.write("\n}\n\n")
print(f"read {f.tell()} bytes from {sys.argv[1]}: writing {fw.tell()} bytes to {sys.argv[2]}...")
f.close() # Close the file
# Write the resultant code to a file that can be compiled
fw.close()