英文:
Is there a ReadLine equivalent for a file in Go?
问题
你可以使用ioutil.ReadFile
函数来读取文本文件的内容,然后使用bytes.Split
函数将内容按照换行符进行分割,最后取得第一个分割后的部分即可。这样就可以实现在不使用bufio
的情况下读取文件直到遇到换行符为止。以下是示例代码:
package main
import (
"bytes"
"fmt"
"io/ioutil"
)
func main() {
filePath := "your_file_path.txt"
content, err := ioutil.ReadFile(filePath)
if err != nil {
fmt.Println("读取文件失败:", err)
return
}
lines := bytes.Split(content, []byte("\n"))
if len(lines) > 0 {
firstLine := lines[0]
fmt.Println(string(firstLine))
}
}
请将your_file_path.txt
替换为你要读取的文件路径。这段代码会读取文件的内容,并将其按照换行符进行分割,然后输出第一行的内容。
英文:
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?
答案1
得分: 2
有很多方法可以实现,但我建议使用bufio
进行包装。但如果这对你不起作用(为什么不起作用?),你可以继续像这样逐个字节地读取:
完整的工作示例:
package main
import (
"bufio"
"bytes"
"fmt"
"io"
)
// ReadLine 从 io.Reader 中读取以 \n 分隔的一行
// 与 bufio 不同,它通过逐个字节地读取来实现,效率较低
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
英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论