Your code is too complex and error prone.
Reading in a loop and checking only for eof is a logical mistake, as it will lead to an endless loop if there is an error while reading (for some reason).
Instead, you need to check all the flow failure states, which you can do by simply checking the istream object istream .
Since this is already returned by the read function, you can (and really should) structure any reading cycle as follows:
while (myFile.read(buffer, aBlock)) process(buffer, aBlock); process(buffer, myFile.gcount());
This is shorter at the same time, does not hide errors and is more readable, since check-stream-state-in-loop is the established C ++ idiom.
source share