I want to write something to a file then read them from the same *os.File pointer. But nothing is read
package main
import (
"bufio"
"fmt"
"io"
"os"
)
func main() {
filename := "test.txt"
f, _ := os.OpenFile(filename, os.O_CREATE|os.O_TRUNC|os.O_RDWR, os.ModePerm)
defer os.Remove(filename)
// write 10 times
for i := 0; i < 10; i++ {
fmt.Fprintf(f, "test%d\n", i)
}
// read 10 times
r := bufio.NewReader(f)
for i := 0; i < 10; i++ {
str, _, err := r.ReadLine()
if err != nil {
if err == io.EOF {
fmt.Println("Done")
return
}
fmt.Println("Error", err)
}
fmt.Println("Read", string(str))
}
}
The program always print "Done" text
When you write to an os.File it moves the current file position pointer. It means after the write file loop the file pointer is at the end of the file.
Now if you try to read from the file you as expected get io.EOF instantly, because you're at the end of the file.
To resolve it you must Seek to the beginning of the file first, before you read from it.
_, err := f.Seek(0, 0)
if err != nil {
fmt.Println("Error", err)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With