Home >Backend Development >Golang >How to Read Data Written to a Temp File in Go?
Reading Data Written to a Temp File in Go
In Go, creating and reading from a temporary file can present challenges. Consider the following simplified test code:
package main import ( "bufio" "fmt" "io/ioutil" "log" "os" "path/filepath" ) func main() { tmpFile, err := ioutil.TempFile("", fmt.Sprintf("%s-", filepath.Base(os.Args[0]))) if err != nil { log.Fatal("Could not create temporary file", err) } fmt.Println("Created temp file:", tmpFile.Name()) defer tmpFile.Close() fmt.Println("Writing some data to the temp file") if _, err = tmpFile.WriteString("test data"); err != nil { log.Fatal("Unable to write to temporary file", err) } else { fmt.Println("Data should have been written") } fmt.Println("Trying to read the temp file now") s := bufio.NewScanner(tmpFile) for s.Scan() { fmt.Println(s.Text()) } err = s.Err() if err != nil { log.Fatal("error reading temp file", err) } }
While the code correctly creates and writes to the temp file, attempting to read results in an empty output. This is because the write operation moves the pointer to the end of the file. To read the data, we need to seek back to the beginning.
Solution:
To resolve this issue, add tmpFile.Seek(0, 0) to move the pointer back to the start of the file before attempting to read:
tmpFile.Seek(0, 0) s := bufio.NewScanner(tmpFile) for s.Scan() { fmt.Println(s.Text()) }
With this modification, the code reads and prints the data correctly. Remember to close the file using defer tmpFile.Close() before exiting to ensure proper resource management.
The above is the detailed content of How to Read Data Written to a Temp File in Go?. For more information, please follow other related articles on the PHP Chinese website!