在 Go 中,我尝试将数据写入临时文件,然后转身读取该文件,但没有成功。下面是一个精简的测试程序。我已通过检查临时文件验证数据是否已写入文件。所以,至少我知道数据正在进入文件。我只是无法读出它。
提前谢谢你的帮助
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 os.Remove(tmpFile.Name())
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 …Run Code Online (Sandbox Code Playgroud)