Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

file

go

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

like image 432
Hau Ma Avatar asked Oct 20 '25 17:10

Hau Ma


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)
}
like image 199
zerkms Avatar answered Oct 23 '25 06:10

zerkms