英文:
writing to a file and reading from it immediate gets no data
问题
我正在尝试将数据写入文件并立即从中读取。我使用读/写模式打开文件,以允许我从中读取和写入。
file1, err := os.OpenFile(fileLocation, os.O_RDWR|os.O_CREATE|os.O_SYNC, 0755)
我可以使用以下代码将数据写入文件:
data := []byte("9\n")
file1.Write(data)
但是,当我尝试使用scanner从文件中读取时,无法获取数据。
scanner := bufio.NewScanner(file1)
scanner.Scan()
fmt.Println(scanner.Text())
我还尝试在尝试读取之前执行fsync操作。
如果在尝试读取之前再次使用file1.Open()打开文件,我就能够获取文件内容。
我在这里漏掉了什么?
英文:
I am trying to write data to a file and immediately read from it. I am opening the file using read/Write mode to allow me to read and write from it.
file1, err := os.OpenFile(fileLocation, os.O_RDWR|os.O_CREATE|os.O_SYNC, 0755)
I am able to write to it using
data := []byte("9\n")
file1.Write(data)
But when I try to read from the file using a scanner, I am unable for to get the data.
scanner := bufio.NewScanner(file1)
scanner.Scan()
fmt.Println(scanner.Text())
I have tried doing fsync before trying to read it as well.
If I open the file again using file1.Open() before trying to read it, I am able to get the contents.
What am I missing here
答案1
得分: 4
在将数据写入文件后,文件偏移量位于文件末尾。如果你想从同一个打开的文件中读取数据,你需要将偏移量重置为文件的开头:
file1.Seek(0, 0)
之后,你就可以从同一个 os.File
对象的文件开头开始读取数据。
英文:
After you have written data to the File, the file offset is at the end of the file. If you want to read from the same open File, you need to reset the offset to the start of the file:
file1.Seek(0, 0)
After that, you can read from the start of the file on the same os.File
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论