2 回答

TA貢獻(xiàn)1828條經(jīng)驗(yàn) 獲得超3個(gè)贊
ioutil.TempFile創(chuàng)建一個(gè)臨時(shí)文件并打開文件進(jìn)行讀寫并返回結(jié)果*os.File(文件描述符)。因此,當(dāng)您在文件中寫入時(shí),指針會(huì)移動(dòng)到該偏移量,即,它當(dāng)前位于文件末尾。但是由于您的要求是從文件中讀取的,您需要Seek使用方法返回到開頭或任何所需的偏移量*os.File.Seek。因此,添加tmpFile.Seek(0, 0)將為您提供所需的行為。
另外,作為一個(gè)好習(xí)慣,不要忘記關(guān)閉文件。請(qǐng)注意,我使用defer tmpFile.Close()了在退出之前關(guān)閉文件的方法。
請(qǐng)參考以下示例:
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)
}
defer tmpFile.Close()
fmt.Println("Created temp file: ", 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 the temp file now")
// Seek the pointer to the beginning
tmpFile.Seek(0, 0)
s := bufio.NewScanner(tmpFile)
for s.Scan() {
fmt.Println(s.Text())
}
if err = s.Err(); err != nil {
log.Fatal("error reading temp file", err)
}
}
更新:來自 OP 的評(píng)論:
鑒于刪除實(shí)際文件也被延遲,是否需要延遲關(guān)閉?如果是這樣,我想延期的順序很重要。
所以,這是一個(gè)很好的問題。所以基本的經(jīng)驗(yàn)法則是關(guān)閉文件然后刪除。因此,甚至可以先刪除然后關(guān)閉它,但這取決于操作系統(tǒng)。
如果您參考C++ 的文檔:
如果文件當(dāng)前由當(dāng)前進(jìn)程或其他進(jìn)程打開,則此函數(shù)的行為是實(shí)現(xiàn)定義的(特別是,POSIX 系統(tǒng)取消鏈接文件名,盡管文件系統(tǒng)空間不會(huì)回收,即使這是最后一次硬鏈接到文件直到最后運(yùn)行的進(jìn)程關(guān)閉文件,Windows 不允許刪除文件)
因此,在 Windows 上,如果您先嘗試刪除它而不關(guān)閉它,那肯定會(huì)出現(xiàn)問題。
所以,因?yàn)閐efer's 是堆疊的,所以執(zhí)行的順序是
defer os.Remove(tmpFile.Name()) // Called 2nd
defer tmpFile.Close() // Called 1st

TA貢獻(xiàn)1860條經(jīng)驗(yàn) 獲得超8個(gè)贊
package main
import (
"fmt"
"io/ioutil"
"log"
)
func main() {
content, err := ioutil.ReadFile("testdata/hello")
if err != nil {
log.Fatal(err)
}
fmt.Printf("File contents: %s", content)
根據(jù) golang 官方文檔。
- 2 回答
- 0 關(guān)注
- 132 瀏覽
添加回答
舉報(bào)