Go中的文件是否有ReadLine等价物?

时间:2014-04-25 03:15:34

标签: go

我希望ReadBytes直到" \ n"对于文本文件,而不是bufio。

有没有办法在不转换为bufio的情况下执行此操作?

1 个答案:

答案 0 :(得分:2)

有很多方法可以做到这一点,但我建议用bufio包装。但如果这对你不起作用(为什么不呢?),你可以继续读取这样的单个字节:

完整的工作示例:

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
        }
    }
}

<强>输出:

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

游乐场: http://play.golang.org/p/dfb0GHPpnm