Standard library / os
os.CreateTemp()
Opens a uniquely named temporary file with restrictive permissions before umask; close and remove it when finished. Example uses a disposable temporary workspace. Expected stdout: 'true\n'.
Formal Syntax & Structure
go syntaxgo
func CreateTemp(dir, pattern string) (*File, error)Parameters & Attributes
| Name | Type | Description |
|---|---|---|
| dir | string | Directory pathname. |
| pattern | string | Shell-style matching pattern. |
Return Value
(*File, error)
Opens a uniquely named temporary file with restrictive permissions before umask; close and remove it when finished.
Working Example
Example Snippetgo
package main
import ( "fmt" "os" "path/filepath" "strings")
func check(e error) { if e != nil { panic(e) }}func workspace() func() { root, e := os.MkdirTemp("", "bytemind-go-") check(e) old, e := os.Getwd() check(e) check(os.Chdir(root)) return func() { check(os.Chdir(old)); check(os.RemoveAll(root)) }}func main() { defer workspace()() f, e := os.CreateTemp(".", "lab-*") check(e) defer os.Remove(f.Name()) check(f.Close()) fmt.Println(strings.HasPrefix(filepath.Base(f.Name()), "lab-"))}