Guido Tarsia
Guido Tarsia

Reputation: 2162

C++ reading buffer size

Suppose that this file is 2 and 1/2 blocks long, with block size of 1024.

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

The third time it reads, it is going to write half of the buffer, leaving the other half with invalid data. Is there a way to know how many bytes did it actually write to the buffer?

Upvotes: 3

Views: 5427

Answers (3)

Konrad Rudolph
Konrad Rudolph

Reputation: 545588

Your code is both overly complicated and error-prone.

Reading in a loop and checking only for eof is a logic error since this will result in an infinite loop if there is an error while reading (for whatever reason).

Instead, you need to check all fail states of the stream, which can be done by simply checking for the istream object itself.

Since this is already returned by the read function, you can (and, indeed, should) structure any reader loop like this:

while (myFile.read(buffer, aBlock))
    process(buffer, aBlock);
process(buffer, myFile.gcount());

This is at the same time shorter, doesn’t hide bugs and is more readable since the check-stream-state-in-loop is an established C++ idiom.

Upvotes: 5

Etienne de Martel
Etienne de Martel

Reputation: 36852

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

Upvotes: 0

Nemo
Nemo

Reputation: 71525

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

Upvotes: 8

Related Questions