如何在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 ?

查看全部
dongshengyin0147
dongshengyin0147
2016/12/18 12:33
  • file
  • io
  • eof
  • 点赞
  • 收藏
  • 回答
    私信
满意答案
查看全部

1个回复