Home >Backend Development >Golang >How to Avoid `io.EOF` When Reading After Writing to the Same `os.File` in Go?
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.
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!