ReadDir Lists Directories In Sorted Order
List one directory level with os.ReadDir, whose entries arrive sorted by name, then filter by extension and read each file size through DirEntry.Info.
Code
package main
import (
"fmt"
"os"
"path/filepath"
"strings"
)
func main() {
root, err := os.MkdirTemp("", "listing-")
if err != nil {
panic(err)
}
defer os.RemoveAll(root)
files := []string{"report.log", "zeta.log", "alpha.txt", "beta.log"}
for _, name := range files {
if err := os.WriteFile(filepath.Join(root, name), []byte("x"), 0o600); err != nil {
panic(err)
}
}
// ReadDir 只列一层,条目保证按文件名排序
entries, err := os.ReadDir(root)
if err != nil {
panic(err)
}
// Type().IsDir() 判目录,Name() 取文件名,Info() 按需取大小
for _, entry := range entries {
if entry.Type().IsDir() || !strings.HasSuffix(entry.Name(), ".log") {
continue
}
info, err := entry.Info()
if err != nil {
panic(err)
}
fmt.Printf("%s %d bytes
", entry.Name(), info.Size())
}
}Execution shape
ReadDir Lists Directories In Sorted Order reduces to the function main.
for _, name := range files is the loop that carries the per-item work. Every err != nil branch (4 sites) calls panic(err) — the run stops at the first failure instead of continuing in a broken state. A defer statement pins the cleanup to the function boundary rather than scattering it through the body.
What to watch for
- Failures abort via
panic(err)— nothing is returned for the caller to check, and nothing in the snippet recovers.
Core lines
for _, entry := range entries {
if entry.Type().IsDir() || !strings.HasSuffix(entry.Name(), ".log") {
continue
}
info, err := entry.Info()
if err != nil {
panic(err)
}
fmt.Printf("%s %d bytes
", entry.Name(), info.Size())
}
for _, name := range files {
if err := os.WriteFile(filepath.Join(root, name), []byte("x"), 0o600); err != nil {
panic(err)
}
}
defer os.RemoveAll(root)
Interactive Tools for This Topic
cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.Git Conventional Commit BuilderBuild and validate Conventional Commits v1.0.0 messages with type, scope, breaking markers, 72-char subject counter, body, footers, and git CLI command.Glob Pattern TesterCompile glob patterns with *, **, ?, character classes, and braces into regex and test them against a list of candidate file paths.Tar Archive Command BuilderBuild safe tar create, extract, and list commands for gzip, xz, zstd, and bzip2 archives with excludes, target directory (-C), and flag explanations.
FAQ
- How does the code signal failure?
- Through `panic(err)` — the 4 checkpoints test `err` and abort the run on the first non-nil one.
- How do you run ReadDir Lists Directories In Sorted Order?
- Direct execution is enough; the script has no external requirements.
Report a problem with this exampleOpens a pre-filled issue on GitHub.