Go os.Stat and FileMode.IsRegular
Distinguish regular files from directories.
A simple example
os.Stat and FileMode.IsRegular
- Start with A regular file a.txt
- Do this Test whether it is a directory
- Result No
Syntax
info.Mode().IsRegular()
Run these examples in Go
Save one example at a time as main.go. Use Go 1.21 or later.
go run main.goTell an uploaded file apart from its folder
A registration desk receives documents through an upload folder. The clerk needs to confirm that the submitted entry is a regular file and that the enclosing location is a directory before processing the batch.
package main
import (
"os"
"fmt"
"path/filepath"
)
func check(err error) {
if err != nil { panic(err) }
}
func main() {
dir, err := os.MkdirTemp("", "lesson-")
check(err)
defer os.RemoveAll(dir)
p := func(name string) string { return filepath.Join(dir, name) }
check(os.WriteFile(p("upload"), nil, 0600))
file, err := os.Stat(p("upload"))
check(err)
folder, err := os.Stat(dir)
check(err)
if file.Mode().IsRegular() && folder.IsDir() { fmt.Println("file and folder") }
}
file and folder
The upload and its enclosing workspace have different entry types.
Locate a rehearsal score
The choir stores each score inside a season folder. A clerk creates an ordinary file at the given location. Which entry type should the status check report?
Locate a workshop handout
An instructor stores the current template in a class folder. A clerk creates an ordinary file at the given location. Which entry type should the status check report?
What to watch for
Status checks describe the instant of inspection. Handle failure at the subsequent open.