Video Coming Soon...
43: ls
This exercise is pending. Quick notes about this exercise:
- My implemention is at https://lcthw.dev/go/go-coreutils
- https://www.gnu.org/software/coreutils/manual/html_node/ls-invocation.html
- os -- https://pkg.go.dev/os@go1.25.3
- path -- probably all of them use it
- regex -- https://pkg.go.dev/regexp@go1.25.3
The Code
View Source file go-coreutils/ls/main.go Only
package main
import (
"fmt"
"io/fs"
"path/filepath"
"flag"
)
func main() {
var recurse bool
flag.BoolVar(&recurse, "R", false, "recursive listing")
flag.Parse()
paths := flag.Args()
if len(paths) == 0 {
paths = append(paths, ".")
}
for _, what := range paths {
if flag.NArg() > 1 {
fmt.Printf("\n%s:\n", what)
}
filepath.WalkDir(what, func (path string, d fs.DirEntry, err error) error {
if path == what { return nil }
if d.IsDir() && recurse {
fmt.Printf("\n%s:\n", path)
} else if d.IsDir() {
fmt.Printf("%s\n", filepath.Base(path))
return fs.SkipDir
} else {
fmt.Printf("%s\n", filepath.Base(path))
}
return nil
})
}
}
Register for Learn Go the Hard Way
Register today for the course and get the all currently available videos and lessons, plus all future modules for no extra charge.