gobyexample/tmp/tmp.go

38 lines
770 B
Go
Raw Normal View History

2024-05-04 08:53:13 +00:00
package tmp
import (
"fmt"
"os"
"path/filepath"
"strconv"
)
func check(err error) {
if err != nil {
panic(err)
}
}
func Tmp() {
f, err := os.CreateTemp("", "gobyexample")
check(err)
fmt.Println("Created tmp file", f.Name())
defer os.Remove(f.Name())
n1, err := f.WriteString("test")
check(err)
fmt.Println("Wrote", n1, "bytes")
dirPath, err := os.MkdirTemp("", "gobyexample")
check(err)
fmt.Println("Created temp dir at", dirPath)
defer os.RemoveAll(dirPath)
err = os.WriteFile(filepath.Join(dirPath, "file1"), []byte("tmpdir file"), 0600)
check(err)
fmt.Println("Stuff written to tmp file inside", dirPath)
b1, err := os.ReadFile(filepath.Join(dirPath, "file1"))
check(err)
fmt.Println(strconv.Quote(string(b1)), "was written to file")
}