Go · lesson 24 of 30 · Files and errorsWalk through folders
filepath.WalkDir visits every file, slices.SortFunc puts the largest first.
24-largest-files.go Download 24-largest-files.go
package main
import (
"cmp"
"fmt"
"io/fs"
"os"
"path/filepath"
"slices"
)
type File struct {
Path string
Size int64
}
func main() {
if len(os.Args) != 2 {
fmt.Println("usage: 24-largest-files FOLDER")
os.Exit(2)
}
var files []File
err := filepath.WalkDir(os.Args[1], func(path string, entry fs.DirEntry, err error) error {
if err != nil || !entry.Type().IsRegular() {
return err
}
info, err := entry.Info()
if err == nil {
files = append(files, File{path, info.Size()})
}
return err
})
if err != nil {
fmt.Println(err)
os.Exit(1)
}
slices.SortFunc(files, func(a, b File) int { return cmp.Compare(b.Size, a.Size) })
for _, f := range files[:min(3, len(files))] {
fmt.Printf("%8d %s\n", f.Size, f.Path)
}
}
Terminal
$ ./24-largest-files photos
15800 photos/wedding.mov
7300 photos/trip.mp4
4200 photos/beach.jpgExercise
Take the number of rows as an option.
TurboShell does not contain Go. These programs are made in Bucket & Code with its Go runtime; the finished file runs on the NAS without Go.