3

I want to ReadBytes until "\n" for a text file, not a bufio.

Is there a way to do this without converting to a bufio?

Aniruddh Chaturvedi
  • 623
  • 3
  • 9
  • 19

1 Answers1

2

There are many ways to do it, but wrapping with bufio is what I would suggest. But if that doesn't work for you (why not?), you can go ahead and read single bytes like this:

Full working example:

package main

import (
    "bytes"
    "fmt"
    "io"
)

// ReadLine reads a line delimited by \n from the io.Reader
// Unlike bufio, it does so rather inefficiently by reading one byte at a time
func ReadLine(r io.Reader) (line []byte, err error) {
    b := make([]byte, 1)
    var l int
    for err == nil {
        l, err = r.Read(b)
        if l > 0 {
            if b[0] == '\n' {
                return
            }
            line = append(line, b...)
        }
    }
    return
}

var data = `Hello, world!
I will write
three lines.`

func main() {

    b := bytes.NewBufferString(data)

    for {
        line, err := ReadLine(b)
        fmt.Println("Line: ", string(line))
        if err != nil {
            return
        }
    }
}

Output:

Line:  Hello, world!
Line:  I will write
Line:  three lines.

Playground: http://play.golang.org/p/dfb0GHPpnm

ANisus
  • 74,460
  • 29
  • 162
  • 158