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
CodePudding user response:
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
.