我想读取文本文件的 ReadBytes 直到 "\n",而不是 bufio。
有没有办法在不转换为 bufio 的情况下做到这一点?
最佳答案
有很多方法可以做到这一点,但我建议使用 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.
Playground : http://play.golang.org/p/dfb0GHPpnm
关于go - Go 中是否有等效于文件的 ReadLine?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23283549/