C ++ Read Buffer Size

Suppose this file has a length of 2 and 1/2 blocks with a block size of 1024.

aBlock = 1024; char* buffer = new char[aBlock]; while (!myFile.eof()) { myFile.read(buffer,aBlock); //do more stuff } 

The third time he reads, he is going to write half the buffer, leaving the second half with invalid data. Is there a way to find out how many bytes it actually wrote into the buffer?

+3
source share
3 answers

istream :: gcount returns the number of bytes read by the previous read.

+7
source

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.

+5
source

You can also look at istream::readsome , which actually returns the number of bytes read.

0
source

Source: https://habr.com/ru/post/891181/


All Articles