我想要使用流(ifstream和ofstream)读取文件(任何文件,小而大)。
我使用跟随功能,此功能适用于中小型文件
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();
}
是正确的吗?
坦克你帮帮我答案 0 :(得分:0)
除了32位限制外,代码还有两大缺陷。
a)你的代码是错误的,所以只需要时间修复它。 (例如,Struct StreamPacket必须是&#34; struct&#34;小写..
b)自1970年RAM非常有限以来,文件背后的逻辑是读取块,处理它,FREE /重用缓冲区和循环。它允许使用非常有限的小占用空间来管理甚至数据TB。
所以主要的想法是重新思考你的代码使用这个逻辑。 可能写起来比较复杂,但是在JS / Web应用程序中思考管理文件是错误。
建议使用大文件作为内存:内存映射文件。
(例如:mmap() vs. reading blocks)
或在windows下存在类似的功能。