os.MkdirTemp, os.WriteFile, os.ReadFile, os.Stat, os.RemoveAll
func MkdirTemp(dir, pattern string) (string, error)
func WriteFile(name string, data []byte, perm FileMode) error
func ReadFile(name string) ([]byte, error)
func Stat(name string) (FileInfo, error)
func RemoveAll(path string) errorCreate a temporary directory, write and read a file inside it, and inspect size and permission bits after umask.
| Parameter | Description |
|---|---|
dir, pattern | MkdirTemp creates a directory in dir. An empty dir uses the default temporary directory. A "*" in pattern is replaced by the random suffix. |
name, data, perm | WriteFile writes data to name with mode perm before umask when it creates the file. |
Returns: MkdirTemp returns the new directory path. WriteFile returns an error on failure. ReadFile returns the file contents. Stat returns a FileInfo. RemoveAll removes the path and any children.
Errors
*os.PathError— Failed file operations from this package are often of type *PathError, with Op, Path, and Err fields. Check them with errors.Is rather than by matching Path or the error text.
- The printed permission 0o644 was measured on this host after WriteFile with perm 0o644. A different umask can produce a different mode.
- The examples never print the temporary path, so the random directory name does not appear in the output.
package main
import (
"fmt"
"os"
"path/filepath"
)
func main() {
dir, err := os.MkdirTemp("", "os-ref-")
if err != nil {
fmt.Println(err)
return
}
defer os.RemoveAll(dir)
name := filepath.Join(dir, "note.txt")
err = os.WriteFile(name, []byte("hi"), 0o644)
fmt.Println(err)
data, err := os.ReadFile(name)
fmt.Printf("%q %v\n", data, err)
info, err := os.Stat(name)
fmt.Printf("%d %#o %v\n", info.Size(), info.Mode().Perm(), err)
}Expected output
<nil>
"hi" <nil>
2 0644 <nil>