Introduction
The typical file system is a hierarchy of files containing files.
A simple first pass is to just list the files in a directory.
f, err := os.Open("/usr/local")
if err != nil {
panic(err)
}
names, err := f.Readdirnames(MAXDIRS)
if err != nil {
panic(err)
}
for _, d := range names {
fmt.Println(d)
}
It’s a simple extension to recurse into actual directories. But we want to make sure we only recurse into directories, and not just attempt it on any file, so we check that first.
package main
import (
"os"
"fmt"
)
const (
MAXDIRS = 1000
)
func walk(dir string) {
f, err := os.Open(dir)
if err != nil {
panic(err)
}
files, err := f.Readdir(MAXDIRS)
if err != nil {
panic(err)
}
for _, fi := range files {
fmt.Printf("%s/%s\n", dir, fi.Name())
if fi.IsDir() {
walk(fmt.Sprintf("%s/%s", dir, fi.Name()))
}
}
}
func main() {
walk("/usr/local")
}
Simple pass. TODO: Add filepath