C++ reading buffer size

邮差的信 提交于 2019-12-12 15:43:46

问题


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?


回答1:


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




回答2:


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.




回答3:


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



来源:https://stackoverflow.com/questions/6444876/c-reading-buffer-size

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!