Create Temporary File in Go

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

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

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

func main() {

    // The easiest way to create a temporary file is by calling ioutil.TempFile.
    // It creates a file and opens it for reading and writing. We provide "" as the first argument,
    // so ioutil.TempFile will create the file in the default location for our OS.
    f, err := ioutil.TempFile("", "sample")
    check(err)

    // Display the name of the temporary file.
    // On Unix-based OSes the directory will likely be /tmp.
    // The file name starts with the prefix given as the second argument to ioutil.TempFile
    // and the rest is chosen automatically to ensure that concurrent calls will always
    // create different file names.
    fmt.Println("Temp file name:", f.Name())

    // Clean up the file after we’re done. The OS is likely to clean up temporary files by itself after some time,
    // but it’s good practice to do this explicitly.
    defer os.Remove(f.Name())

    _, err = f.Write([]byte{1, 2, 3, 4})
    check(err)
}