GO語言"io/ioutil"包中"TempFile"函數的用法及代碼示例。
用法:
func TempFile(dir, pattern string)(f *os.File, err error)
TempFile在目錄dir中新建一個臨時文件,打開文件進行讀寫,並返回生成的*os.File。文件名是通過采用模式並在末尾添加一個隨機字符串來生成的。如果模式包含"*",則隨機字符串替換最後的"*"。如果 dir 是空字符串,TempFile 使用臨時文件的默認目錄(參見 os.TempDir)。多個程序同時調用TempFile 不會選擇同一個文件。調用者可以使用 f.Name() 來查找文件的路徑名。不再需要時刪除文件是調用者的責任。
從 Go 1.17 開始,此函數僅調用 os CreateTemp
例子:
package main
import (
"io/ioutil"
"log"
"os"
)
func main() {
content := []byte("temporary file's content")
tmpfile, err := ioutil.TempFile("", "example")
if err != nil {
log.Fatal(err)
}
defer os.Remove(tmpfile.Name()) // clean up
if _, err := tmpfile.Write(content); err != nil {
log.Fatal(err)
}
if err := tmpfile.Close(); err != nil {
log.Fatal(err)
}
}
示例(後綴):
package main
import (
"io/ioutil"
"log"
"os"
)
func main() {
content := []byte("temporary file's content")
tmpfile, err := ioutil.TempFile("", "example.*.txt")
if err != nil {
log.Fatal(err)
}
defer os.Remove(tmpfile.Name()) // clean up
if _, err := tmpfile.Write(content); err != nil {
tmpfile.Close()
log.Fatal(err)
}
if err := tmpfile.Close(); err != nil {
log.Fatal(err)
}
}
相關用法
- GO Template用法及代碼示例
- GO TempDir用法及代碼示例
- GO Template.Delims用法及代碼示例
- GO TeeReader用法及代碼示例
- GO Time.Sub用法及代碼示例
- GO TrailingZeros8用法及代碼示例
- GO Tx.ExecContext用法及代碼示例
- GO Time.Equal用法及代碼示例
- GO ToTitle用法及代碼示例
- GO Time.After用法及代碼示例
- GO Title用法及代碼示例
- GO TrimRight用法及代碼示例
- GO ToLowerSpecial用法及代碼示例
- GO Time.Format用法及代碼示例
- GO ToUpper用法及代碼示例
- GO Trunc用法及代碼示例
- GO TrailingZeros32用法及代碼示例
- GO To用法及代碼示例
- GO Time.AppendFormat用法及代碼示例
- GO Time.AddDate用法及代碼示例
注:本文由純淨天空篩選整理自golang.google.cn大神的英文原創作品 TempFile。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。