Home > Backend Development > Golang > How to Correctly Read Data After Writing to a File Using a Single *os.File in Go?

How to Correctly Read Data After Writing to a File Using a Single *os.File in Go?

Barbara Streisand
Release: 2024-12-16 00:31:09
Original
270 people have browsed it

How to Correctly Read Data After Writing to a File Using a Single *os.File in Go?

Handling File Read and Write Operations with a Single *os.File in Go

This question highlights a common challenge in working with files in Go, where writing to a file moves the current position pointer, potentially preventing subsequent read operations from retrieving the expected data.

In the provided code, the program aims to write 10 lines of text to a file named "test.txt" and then read them back. However, the code doesn't read any data and instead continuously prints "Done" due to an io.EOF error.

To understand the issue, it's crucial to note that writing to an os.File modifies the file position pointer. After completing the write loop, the pointer is located at the end of the file. When the program attempts to read the file, it starts at the current position. Since the pointer is at the end, it instantly encounters io.EOF, signifying the end of the file.

To remedy this problem, one must reset the file position pointer to the beginning before attempting to read. This can be achieved using the Seek method, as demonstrated in the modified code below:

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)
    }
    // reset file pointer
    _, 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))
    }
}
Copy after login

By correctly handling the file position pointer, the program can now successfully read the written data from the file.

The above is the detailed content of How to Correctly Read Data After Writing to a File Using a Single *os.File in Go?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template