Stat Files To Check Existence And Type

Classify a path before use with os.Stat: distinguish missing files, directories, regular files, and errors through errors.Is and the mode bits.

GoCli Tooling

Code

gosnippet
56 lines
package main

import (
	"errors"
	"fmt"
	"io/fs"
	"os"
	"path/filepath"
)

// describe classifies one stat call into a printable form
func describe(path string, statFn func(string) (os.FileInfo, error)) string {
	info, err := statFn(path)
	switch {
	case errors.Is(err, fs.ErrNotExist):
		return "missing"
	case err != nil:
		return "stat error: " + err.Error()
	case info.IsDir():
		return fmt.Sprintf("directory, mode %s", info.Mode())
	case !info.Mode().IsRegular():
		return fmt.Sprintf("special file, mode %s", info.Mode())
	default:
		return fmt.Sprintf("regular file, %d bytes, mode %s", info.Size(), info.Mode())
	}
}

func main() {
	dir, err := os.MkdirTemp("", "stat-types-*")
	if err != nil {
		fmt.Println(err)
		return
	}
	defer os.RemoveAll(dir)

	file := filepath.Join(dir, "notes.txt")
	if err := os.WriteFile(file, []byte("hello"), 0o644); err != nil {
		fmt.Println(err)
		return
	}

	// one function covers three outcomes: missing / directory / regular file
	for _, target := range []string{file, dir, filepath.Join(dir, "absent.txt")} {
		fmt.Printf("%-10s -> %s\n", filepath.Base(target), describe(target, os.Stat))
	}

	// Lstat does not follow symlinks: the link itself shows up as a special
	// file, while Stat follows it and reports the target file
	link := filepath.Join(dir, "link.txt")
	if err := os.Symlink(file, link); err != nil {
		fmt.Println("symlink unavailable on this platform:", err)
		return
	}
	fmt.Printf("%-10s -> %s\n", "link.txt", describe(link, os.Stat))
	fmt.Printf("%-10s -> %s\n", "link.txt", describe(link, os.Lstat))
}

How it works

The working surface is the functions describe and main — everything else is wiring.

The cycling part of this snippet is for _, target := range []string{file, dir, filepath.Join(dir, "absent.txt")}. Every fallible call checks err != nil (3 sites), so an error is handled where it happens rather than bubbling invisibly. The cleanup call is deferred to function exit — success, early return, and panic all covered.

What to watch for

  • Error values are returned, not thrown — every call site must inspect err before using the other return values.

Using it

The entry-point signature is func describe(path string, statFn func(string) (os.FileInfo, error)) string

Output lines are prefixed (symlink unavailable on this platform:), keeping the connection between steps and their output lines intact.

The sequence describe lives in main; running the file triggers it.

Key statements

return fmt.Sprintf("regular file, %d bytes, mode %s", info.Size(), info.Mode())
return fmt.Sprintf("special file, mode %s", info.Mode())
return fmt.Sprintf("directory, mode %s", info.Mode())

Interactive Tools for This Topic

FAQ

Is there exception handling?
No exceptions — `error` returns checked at 3 sites, and callers branch on `err` first.
What does Stat Files To Check Existence And Type print when run?
Running the file directly is enough — expect labeled output lines such as `symlink unavailable on this platform:`.