Я полагаю, что ваша проблема возникает, когда у вас меньше 4096 байт для чтения, и вы вызываете stream.read()
Я использую следующую функцию, которая ПРОБЫВАЕТ прочитать 4096, но исправляет при сбое -может быть, это полезно?
// Tries to read num bytes from inRaw into buffer (space previously allocated). When num bytes does not take
// us off the end of the file, then this does the simple obvious thing and returns true. When num bytes takes
// us over the edge, but things are still sane (they wanted 100 bytes, only 60 bytes to go), then this fills
// as much as possible and leaves things in a nice clean state. When there are zero bytes to go, this
// return false.
bool safeRead(
std::ifstream& inRaw,
char* buffer,
uint16_t num
)
{
auto before = inRaw.tellg();
if (inRaw.read(buffer, num) && inRaw.good() && !inRaw.eof())
{
return true;
}
else
{
if (inRaw.gcount())
{
inRaw.clear();
auto pos = before + std::streamoff(inRaw.gcount());
inRaw.seekg(pos);
return true;
}
else
{
return false;
}
}
}