相关疑难解决方法(0)

读取刚刚写入临时文件的数据

在 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)

go temporary-files

0
推荐指数
1
解决办法
4041
查看次数

标签 统计

go ×1

temporary-files ×1