Write and Read File with same *os.File in Go

Viewed 451

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

1 Answers

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)
}
Related