gpt4 book ai didi

go - bufio.Writer写入后,bufio.Reader不会从文件中读取任何内容

转载 作者:行者123 更新时间:2023-12-01 20:24:45 26 4
gpt4 key购买 nike

代码如下所示:

package main

import (
"bufio"
"fmt"
"io"
"log"
"os"
)

func main() {
file, _ := os.OpenFile("test.txt", os.O_CREATE|os.O_RDWR|os.O_APPEND, 0666)

// write
writer := bufio.NewWriter(file)
for i := 0; i < 10; i++ {
fmt.Fprintln(writer, i)
}
writer.Flush()

// read
reader := bufio.NewReader(file)
for {
line, _, err := reader.ReadLine()
log.Println(string(line))
if err == io.EOF {
break
}
if err != nil {
log.Fatalln("get msg failed.")
}
}
}
我无法读取已写入文件的内容。
似乎文件的偏移量指向文件的末尾。
有人可以解释为什么会这样吗?

最佳答案

O_APPEND使文件描述符的偏移量在每次写入之前前进到文件末尾。每次写操作将文件描述符的偏移量提高成功写入的字节数。
//read行之前添加以下内容:

    offset, _ := file.Seek(0, io.SeekCurrent)
fmt.Printf("DEBUG: before: file offset is %d\n", offset)
file.Seek(0, 0)
offset, _ = file.Seek(0, io.SeekCurrent)
fmt.Printf("DEBUG: after: file offset is %d\n", offset)
您会看到您的程序现在可以正常运行了。

引用:
open的手册页中:
       O_APPEND
The file is opened in append mode. Before each write(2), the
file offset is positioned at the end of the file, as if with
lseek(2). The modification of the file offset and the write
operation are performed as a single atomic step.
write的手册页中:
       For a seekable file (i.e., one to which lseek(2) may be applied, for
example, a regular file) writing takes place at the file offset, and
the file offset is incremented by the number of bytes actually
written. If the file was open(2)ed with O_APPEND, the file offset is
first set to the end of the file before writing. The adjustment of
the file offset and the write operation are performed as an atomic
step.

关于go - bufio.Writer写入后,bufio.Reader不会从文件中读取任何内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62688866/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com