dongshengyin0147
2016-12-18 12:33
浏览 594
已采纳

如何在Go中的io.Reader上测试EOF?

The Go's io.Reader documentation states that a Read() may return a non zero n value and an io.EOF at the same time. Unfortunately, the Read() method of a File doesn't do that.

When the EOF is reached and some bytes could still be read, the Read method of file returns non zero n and nil error. It is only when we try to read when already at the end of the file that we get back zero n and io.EOF as error.

I couldn't find a simple method to test if the EOF is reached without trying to read data from the file. If we perform a Read() with a buffer of 0 byte, we get back zero n and nil error although we are at the end of file.

To avoid this last read, the only solution I have found is to keep track myself of the number of bytes remaining to read in the file. Is there a simpler solution ?

图片转代码服务由CSDN问答提供 功能建议

Go的 io.Reader </ code>文档指出, Read()</ code>可能会同时返回非零的 n </ code>值和 io.EOF </ code>。 不幸的是, File </ code>的 Read()</ code>方法不能做到这一点。 </ p>

达到EOF并且仍然可以读取某些字节时,文件的Read方法返回非零的 n </ code>和 nil </ code>错误 。 只有当我们尝试读取文件末尾的内容时,我们才将零 n </ code>和 io.EOF </ code>返回为错误。 </ p>

我无法找到一种简单的方法来测试是否达到EOF,而不尝试从文件中读取数据。 如果我们使用0字节的缓冲区执行Read(),尽管我们位于文件末尾,但返回的 n </ code>和 nil </ code>错误为零。 </ p>

为避免最后一次读取,我发现的唯一解决方案是跟踪自己要读取的文件剩余字节数。 有没有更简单的解决方案?</ p> </ div>

1条回答 默认 最新

相关推荐 更多相似问题