Home >Backend Development >Golang >How to Avoid `io.EOF` When Reading After Writing to the Same `os.File` in Go?

How to Avoid `io.EOF` When Reading After Writing to the Same `os.File` in Go?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-14 08:53:14265browse

How to Avoid `io.EOF` When Reading After Writing to the Same `os.File` in Go?

Reading and Writing to the Same *os.File in Go

Understanding the Issue

In Go, when writing data to a file using os.File, the file pointer is moved to the end of the file after writing. Subsequently, when attempting to read data from the same file pointer, an immediate io.EOF (End of File) error is encountered because the file pointer is still at the end of the file.

Resolution

To successfully read data from the same file pointer after writing, you must reset the file pointer to the beginning of the file using the Seek method. Here's how you can modify the example code:

// Seek to the beginning of the file before reading
_, err := f.Seek(0, 0)
if err != nil {
    fmt.Println("Error", err)
}

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

By adding the Seek method, the file pointer is reset to the beginning of the file before reading, allowing the subsequent read operations to retrieve the written data without causing an io.EOF error.

The above is the detailed content of How to Avoid `io.EOF` When Reading After Writing to the Same `os.File` in Go?. 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