Reading n bytes from a buffer?

1,119 views
Skip to first unread message

Mostafa Hajizadeh

unread,
Jan 11, 2012, 8:01:20 AM1/11/12
to golan...@googlegroups.com
bufio doesn't have a function to read a specific number of bytes from a Reader. It was easy to write using ReadByte, but I thought having that might be very handy, specially while dealing with protocols and file formats in which you know how many bytes are you going to read, which is a very common case.

minux

unread,
Jan 11, 2012, 8:09:44 AM1/11/12
to golan...@googlegroups.com

On Wed, Jan 11, 2012 at 9:01 PM, Mostafa Hajizadeh <most...@gmail.com> wrote:
bufio doesn't have a function to read a specific number of bytes from a Reader. It was easy to write using ReadByte, but I thought having that might be very handy, specially while dealing with protocols and file formats in which you know how many bytes are you going to read, which is a very common case.
func Read(p []byte) (int, error) will normally read len(p) bytes into p. You just need to provide a slice of required length and check n == len(p)
after it returns.

JONNALAGADDA Srinivas

unread,
Jan 11, 2012, 8:11:57 AM1/11/12
to golan...@googlegroups.com
Mostafa,

        Allocate a buffer of the required size, and send it to `Read'.  The size of the buffer is the specification of the number of bytes to read.  Actually read number can be lower.

                                                            Greetings,
                                                                    JS
____

Jan Mercl

unread,
Jan 11, 2012, 8:12:41 AM1/11/12
to golan...@googlegroups.com
On Wednesday, January 11, 2012 2:01:20 PM UTC+1, Mostafa Hajizadeh wrote:
bufio doesn't have a function to read a specific number of bytes from a Reader. It was easy to write using ReadByte, but I thought having that might be very handy, specially while dealing with protocols and file formats in which you know how many bytes are you going to read, which is a very common case.

I think there already is full control over the upper limit (N) of the number of bytes bufio.Read will read by passing a slice with len() = N.

// Along the lines of e.g.:
var dest = make([]byte, 64*1024)
n, err := myBufioReader.Read(dest[x:x+42]) // At most 42 bytes

Mostafa Hajizadeh

unread,
Jan 11, 2012, 8:30:19 AM1/11/12
to golan...@googlegroups.com
You are all right. My mistake.

Christoph

unread,
Jan 11, 2012, 8:49:04 AM1/11/12
to golang-nuts
If you want to read an exact number of bytes you should use
io.ReadFull(r Reader, buf []byte). It always reads len(buf) bytes. If
an EOF happends and there are still bytes left it returns an
ErrUnexpectedEOF error.
Reply all
Reply to author
Forward
0 new messages