I want read file (any file, tiny and big) with stream (ifstream and ofstream).
I use follow function, this function is good for tiny and medium file
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;
but I can't read big file (example 8 GB) with it, and I have error within while loop, Error is :
Unhandled exception at 0x7703B782 in program.exe: Microsoft C++ exception: std::bad_alloc at memory location 0x004FEEDC.
what is wrong? Where is my problem?
and for write I use this function:
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();
}
is Correct?
tank you for help me