Home >Backend Development >Golang >Why Does Reading After Writing to the Same Go File Pointer Return Nothing?

Why Does Reading After Writing to the Same Go File Pointer Return Nothing?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-13 03:56:09669browse

Why Does Reading After Writing to the Same Go File Pointer Return Nothing?

Reading and Writing to the Same File in Go

In Go, working with files is made simple with the os.File type. However, an issue can arise when trying to read and write to the same file pointer. This article addresses such a scenario and provides a solution.

Problem:

You're attempting to write data to a file, then read it back from the same file pointer. However, the read operation returns nothing.

Code:

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

Issue:

In the provided code, the file pointer is moved to the end of the file after the write operation. When the read operation is attempted, it immediately encounters the end of the file, resulting in an io.EOF error.

Solution:

To resolve this issue, you must manually seek the file pointer back to the beginning before reading from it.

_, err := f.Seek(0, 0)
if err != nil {
    fmt.Println("Error", err)
}

This code snippet adds a Seek operation before the read loop. It sets the file pointer to the beginning of the file, allowing the subsequent read operation to retrieve the written data.

The above is the detailed content of Why Does Reading After Writing to the Same Go File Pointer Return Nothing?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn