Go: Create a temporary file or directory

File

Use ioutil.TempFile in package io/ioutil to create a temporary file:

file, err := ioutil.TempFile("dir", "prefix")
if err != nil {
        log.Fatal(err)
}
defer os.Remove(file.Name())

fmt.Println(file.Name()) // For example "dir/prefix054003078"

The call to ioutil.TempFile

To put the new file in os.TempDir(), the default directory for temporary files, call ioutil.TempFile with an empty directory string.

Directory

Use ioutil.TempDir in package io/ioutil to create a temporary directory:

dir, err := ioutil.TempDir("dir", "prefix")
if err != nil {
        log.Fatal(err)
}
defer os.RemoveAll(dir)

The call to ioutil.TempDir

To put the new directory in os.TempDir(), the default directory for temporary files, call ioutil.TempDir with an empty directory string.

Comments

Be the first to comment!