Use temporary directories and io/fs
Use temporary directories and io/fs
os.MkdirTemp creates a uniquely named directory. io/fs defines a small read-oriented filesystem interface that lets functions read disk files or embedded assets through the same API. Use an absolute temporary root, clean it up after use and keep all fixture writes within it.
package main
import ( "fmt" "io/fs" "os" "path/filepath")
func check(err error) { if err != nil { panic(err) }}func lab() (string, func()) { d, err := os.MkdirTemp("", "bytemind-") check(err) return d, func() { check(os.RemoveAll(d)) }}
func main() { d, cleanup := lab() defer cleanup() check(os.WriteFile(filepath.Join(d, "note.txt"), []byte("hello"), 0600)) var tree fs.FS = os.DirFS(d) b, e := fs.ReadFile(tree, "note.txt") check(e) fmt.Println(string(b))}An fs.FS takes slash-separated, unrooted names; the special name . denotes its root. DirFS adapts a directory to the interface. It does not confine symbolic links to the root. Use only trusted trees in this example. ReadFile loads the entire small file.
Expected output:
helloList entries
package main
import ( "fmt" "io/fs" "os" "path/filepath")
func check(err error) { if err != nil { panic(err) }}func lab() (string, func()) { d, err := os.MkdirTemp("", "bytemind-") check(err) return d, func() { check(os.RemoveAll(d)) }}
func main() { d, cleanup := lab() defer cleanup() for _, n := range []string{"z.txt", "a.txt"} { check(os.WriteFile(filepath.Join(d, n), nil, 0600)) } entries, e := fs.ReadDir(os.DirFS(d), ".") check(e) for _, entry := range entries { fmt.Println(entry.Name(), entry.IsDir()) }}fs.ReadDir returns entries sorted by filename. Check errors before iteration. DirEntry.IsDir can identify directory entries without opening each file; it does not follow symlinks.
Expected output:
a.txt falsez.txt falseTry it locally
Create subdirectory "data" in lab, create data/a.txt containing "ok", then use fs.Sub and fs.ReadFile to print the contents.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Files and paths 04: Use temporary directories and io/fs
Check the lesson objective before moving on.
What name denotes the root of an fs.FS?
Does os.DirFS block symlinks pointing outside its directory?