从golang中的缓冲读取器读取特定数量的字节 [英] Reading specific number of bytes from a buffered reader in golang
问题描述
我知道 bufio 包中的golang中的特定功能。
I am aware of the specific function in golang from the bufio package.
func (b *Reader) Peek(n int) ([]byte, error)
Peek返回下n个字节,不提高阅读器。字节
在下一次读取调用时停止有效。如果Peek返回的字节数少于n
个字节,则它还会返回一个错误,解释为什么读取短。如果n大于b的缓冲区大小,则
错误为ErrBufferFull。
Peek returns the next n bytes without advancing the reader. The bytes stop being valid at the next read call. If Peek returns fewer than n bytes, it also returns an error explaining why the read is short. The error is ErrBufferFull if n is larger than b's buffer size.
我需要能够读取特定数字读取器读取的字节数,将使读取器前进。基本上,与上面的功能相同,但是它使阅读器更高级。有人知道如何做到这一点吗?
I need to be able to read a specific number of bytes from a Reader that will advance the reader. Basically, identical to the function above, but it advances the reader. Does anybody know how to accomplish this?
推荐答案
请注意, bufio.Read
方法最多调用一次底层 io.Read
,这意味着它可以返回 n< len(p)
,但没有达到EOF。如果您想精确地读取 len(p)
个字节或由于错误而失败,则可以使用 io.ReadFull
Note that the bufio.Read
method calls the underlying io.Read
at most once, meaning that it can return n < len(p)
, without reaching EOF. If you want to read exactly len(p)
bytes or fail with an error, you can use io.ReadFull
like this:
n, err := io.ReadFull(reader, p)
即使读取器处于缓冲状态,此方法也有效。
This works even if the reader is buffered.
这篇关于从golang中的缓冲读取器读取特定数量的字节的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!