File tree traversal written in Golang (recursively traverse all folders and files)

main entrance

func main() {
var folder bool
var document bool
var rootPath string
flag.BoolVar(&folder, "r", true, "folder")
flag.BoolVar(&document, "d", false, "document")
flag.StringVar(&rootPath, "rp", "", "Root folder to traverse")
flag.Parse()
if rootPath == "" {
exPath, _ := os.Getwd()
rootPath = exPath
}
filePath := "out.txt"
var err = os.Remove(filePath)
_, err1 := os.Create(filePath)
if err != nil {
return
}
if err != nil && err1 != nil {
return
}
file, err := os.OpenFile(filePath, os.O_WRONLY|os.O_APPEND, 0666)
if err != nil {
fmt.Println("Failed to open file", err)
}
// Close the file handle in time
defer func(file *os.File) {
err = file.Close()
}(file)
write := bufio.NewWriter(file)
getPath(folder, document, rootPath, "", write)
}

file tree logic

func getPath(folder bool, document bool, rootPath string, indent string, write *bufio.Writer) {
files, err := ioutil.ReadDir(rootPath)
if err != nil {
fmt.Println("read file path error", err)
return
}
for i := 0; i < len(files); i++ {
if files[i].Name()[0] == '.' {
files = append(files[:i], files[i+1:]...)
}
}
dirs := make([]string, 0)
if document {
for _, fi := range files {
if !fi.IsDir() {
dirs = append(dirs, fi.Name())
}
}
}
lenFile := len(dirs)
if folder {
for _, fi := range files {
if fi.IsDir() {
dirs = append(dirs, fi.Name())
}
}
}
// branch for the last file with
for i := 0; i < len(dirs); i++ {
if i == len(dirs)-1 {
fmt.Println(indent + "└── " + dirs[i])
_, err := write.WriteString(indent + "└── " + dirs[i] + "\r\n")
if err != nil {
return
}
e := write.Flush()
if e != nil {
return
}
if i >= lenFile {
getPath(folder, document, rootPath+"/"+dirs[i], indent+" ", write)
}
} else {
fmt.Println(indent + "├── " + dirs[i])
_, err := write.WriteString(indent + "├── " + dirs[i] + "\r\n")
if err != nil {
return
}
e := write.Flush()
if e != nil {
return
}
if i >= lenFile {
getPath(folder, document, rootPath+"/"+dirs[i], indent+"│ ", write)
}
}
}
}

go run main.go file_name.go

Golang

Leave a Reply

Your email address will not be published.

en_USEnglish