GO語言"os"包中"MkdirTemp"函數的用法及代碼示例。
用法:
func MkdirTemp(dir, pattern string)(string, error)
MkdirTemp 在目錄 dir 中創建一個新的臨時目錄,並返回新目錄的路徑名。新目錄的名稱是通過在模式末尾添加一個隨機字符串來生成的。如果模式包含 "*",則隨機字符串將替換最後一個 "*"。如果 dir 是空字符串,MkdirTemp 使用默認目錄來存放臨時文件,如 TempDir 返回的多個程序或 goroutines 同時調用 MkdirTemp 將不會選擇相同的目錄。當不再需要目錄時,調用者有責任將其刪除。
例子:
package main
import (
"log"
"os"
"path/filepath"
)
func main() {
dir, err := os.MkdirTemp("", "example")
if err != nil {
log.Fatal(err)
}
defer os.RemoveAll(dir) // clean up
file := filepath.Join(dir, "tmpfile")
if err := os.WriteFile(file, []byte("content"), 0666); err != nil {
log.Fatal(err)
}
}
示例(後綴):
package main
import (
"log"
"os"
"path/filepath"
)
func main() {
logsDir, err := os.MkdirTemp("", "*-logs")
if err != nil {
log.Fatal(err)
}
defer os.RemoveAll(logsDir) // clean up
// Logs can be cleaned out earlier if needed by searching
// for all directories whose suffix ends in *-logs.
globPattern := filepath.Join(os.TempDir(), "*-logs")
matches, err := filepath.Glob(globPattern)
if err != nil {
log.Fatalf("Failed to match %q: %v", globPattern, err)
}
for _, match := range matches {
if err := os.RemoveAll(match); err != nil {
log.Printf("Failed to remove %q: %v", match, err)
}
}
}
相關用法
- GO Mkdir用法及代碼示例
- GO MkdirAll用法及代碼示例
- GO MethodSet用法及代碼示例
- GO MakeFunc用法及代碼示例
- GO Mul32用法及代碼示例
- GO Map用法及代碼示例
- GO MakeTable用法及代碼示例
- GO Modf用法及代碼示例
- GO Mul64用法及代碼示例
- GO Mod用法及代碼示例
- GO MultiReader用法及代碼示例
- GO MultiWriter用法及代碼示例
- GO MarshalIndent用法及代碼示例
- GO Marshal用法及代碼示例
- GO MatchString用法及代碼示例
- GO Month用法及代碼示例
- GO Match用法及代碼示例
- GO PutUvarint用法及代碼示例
- GO Scanner.Scan用法及代碼示例
- GO LeadingZeros32用法及代碼示例
注:本文由純淨天空篩選整理自golang.google.cn大神的英文原創作品 MkdirTemp。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。