我想要读取文件(任何文件,小和大)与流(如果流和流)。
我使用的是跟随函数,这个函数适合于微型和中型文件。
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;但是我不能用它读取大文件(例如8GB),而且我在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();
}是对的?
让你帮我
发布于 2018-01-16 08:17:37
除了32位限制外,该代码还有两个大缺陷。
( a)您的代码有很多错误,所以只需时间就可以修复它。(例如,结构StreamPacket必须是小写的" Struct“)。
( b)自1970年RAM非常有限以来,文件背后的逻辑是以块形式读取、处理、释放/重用缓冲区和循环。
它允许使用非常小的占用空间来管理甚至是TB的数据。
因此,主要的想法是重新考虑您的代码来使用这个逻辑。编写起来可能更复杂,但是像在JS/Web应用程序中那样想管理文件是错误的。
使用大文件作为内存的建议:内存映射文件。
(例如:mmap() vs. reading blocks)
或者在windows下也存在类似的功能。
https://stackoverflow.com/questions/48275831
复制相似问题