Temporary Files and Directories
// Importing necessary packages.
import (
"fmt"
"os"
"path/filepath"
)
// Function to check and panic if an error occurs.
func check(e error) {
if e != nil {
panic(e)
}
}
// Main function where the execution of the program begins.
func main() {
// Creating a temporary file with the prefix "sample" in the default temporary directory.
f, err := os.CreateTemp("", "sample")
check(err)
fmt.Println("Temp file name:", f.Name())
// Defer removing the temporary file at the end of the program.
defer os.Remove(f.Name())
// Writing data to the temporary file.
_, err = f.Write([]byte{1, 2, 3, 4})
check(err)
// Creating a temporary directory with the prefix "sampledir" in the default temporary directory.
dname, err := os.MkdirTemp("", "sampledir")
check(err)
fmt.Println("Temp dir name:", dname)
// Defer removing the temporary directory and its contents at the end of the program.
defer os.RemoveAll(dname)
// Creating a file inside the temporary directory and writing data to it.
fname := filepath.Join(dname, "file1")
err = os.WriteFile(fname, []byte{1, 2}, 0666)
check(err)
}output
Last updated