Create Temporary Directory

Throughout program execution, we often want to create data that isn’t needed after the program exits. Temporary files and directories are useful for this purpose since they don’t pollute the file system over time.

Examples Filter
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)
}
Last Run  :
Temp dir name: /tmp/sampledir562555487