gpt4 book ai didi

c++ - 使用流读取大文件(最多 8 GB)

转载 作者:太空宇宙 更新时间:2023-11-04 12:52:36 26 4
gpt4 key购买 nike

<分区>

我想用流(ifstream 和 ofstream)读取文件(任何文件,无论大小)。

我用的是follow函数,这个函数适合中小文件

Struct StreamPacket
{
long int startOffset;
std::vector<char> data;
}
CONST int STREAM_BUFFER = 15000;
std::ifstream stream;

stream.open(path, std::ios::in | std::ios::binary | std::ios::ate);

if (!stream.is_open())
return std::vector<StreamPacket>();


// create a vector to hold all the bytes in the file
std::vector<StreamPacket> wholePacket;
while (stream.is_open())
{
StreamPacket fileStream;
fileStream.startOffset = stream.tellg();
// read the file
std::vector<char> data(STREAM_BUFFER, 0);
stream.read(&data[0], STREAM_BUFFER);
fileStream.data = data;
wholePacket.push_back(fileStream);
}

stream.close();

return wholePacket;

但是我不能用它读取大文件(例如 8 GB),而且我在 while 循环中有错误,错误是:

Unhandled exception at 0x7703B782 in program.exe: Microsoft C++ exception: std::bad_alloc at memory location 0x004FEEDC.

怎么了?我的问题在哪里?

对于写入我使用这个函数:

void SaveToFile(CString path, CString filename, std::vector<StreamPacket> fileStream)
{
std::ofstream outfile(path + filename, std::ios::out | std::ios::binary);

if (!outfile.is_open())
return;

for (size_t i = 0; i < fileStream.size(); i++)
{
outfile.write(&fileStream[i].data[0], fileStream[i].data.size());
}
int a = 10;

//outfile.write(&fileStream[0], fileStream.size());
outfile.close();
}

是正确的吗?

谢谢你帮帮我

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com