Problem with EOF when determine stream end

前端 未结 1 1466
粉色の甜心
粉色の甜心 2020-12-11 12:43

When I try to determine end of file with function feof(FILE *), I find it does not work as I expected: an extra read is required even if the stream does end. e.

相关标签:
1条回答
  • 2020-12-11 12:59

    Do not use feof() or any variants - it is as simple as that. You want it to somehow predict the next read will fail, but that's not what it does - it tells you what the result of the PREVIOUS read was. The correct way to read a file is (in pseudocode):

    while( read( file, buffer ) ) {
       do something with buffer
    }
    

    In other words, you need to test the result of the read operation. This is true for both C streams and C++ iostreams.

    0 讨论(0)
提交回复
热议问题