Create Temporary Directory in Go

Posted by yhuang
Public (Editable by Users)
Go
Edit
package main

import (
    "fmt"
    "io/ioutil"
    "os"
    "path/filepath"
)

func check(e error) {
    if e != nil {
        panic(e)
    }
}

func main() {

    // If we intend to write many temporary files, we may prefer to create a temporary directory.
    // ioutil.TempDir’s arguments are the same as TempFile’s, but it returns a directory name rather than an open file.
    dname, err := ioutil.TempDir("", "sampledir")
    fmt.Println("Temp dir name:", dname)

    defer os.RemoveAll(dname)

    fname := filepath.Join(dname, "file1")
    err = ioutil.WriteFile(fname, []byte{1, 2}, 0666)
    check(err)
}