通过递归实现打印当前或指定路径下文件的层级结构,暂未实现层级限制选项。
package main
import (
"fmt"
"os"
"sort"
)
func main() {
dirPath := ""
args := os.Args
if len(args) <= 1 {
dirPath = "."
} else {
dirPath = args[1]
}
PrintPathTree(dirPath, []bool{})
}
func PrintPathTree(dirPath string, prefix []bool) {
f, err := os.Open(dirPath)
defer func() {
_ = f.Close()
}()
if err != nil {
fmt.Println("[ERROR] OPEN FAIL. ERR=" + err.Error())
return
}
dirEntry, err := f.ReadDir(-1)
if err != nil {
fmt.Println("[ERROR] ReadDir FAIL. ERR=" + err.Error())
return
}
//保证按文件名字典序展示
sort.SliceStable(dirEntry, func(i, j int) bool {
return dirEntry[i].Name() < dirEntry[j].Name()
})
for index, entry := range dirEntry {
entryName := entry.Name()
if len(prefix) == 0 && index == 0 {
fmt.Println(".")
}
for i := 0; i < len(prefix); i++ {
if prefix[i] {
fmt.Print("│ ")
} else {
fmt.Print(" ")
}
}
if index == len(dirEntry)-1 {
fmt.Println("└──" + entryName)
} else {
fmt.Println("├──" + entry.Name())
}
if entry.IsDir() {
PrintPathTree(dirPath+"/"+entry.Name(), append(prefix, index != len(dirEntry)-1))
continue
}
}
}
效果:
go build -o tree && ./tree /usr/local/go/src/vendor/golang.org/x/text