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.

GoCli Tooling

Code

gosnippet
42 lines
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

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.