Golang iterates over all files in a folder and subfolders

package main
 
import (
"fmt"
"io/ioutil"
)
 
func GetAllFile(pathname string, s []string) ([]string, error) {
rd, err := ioutil.ReadDir(pathname)
if err != nil {
fmt.Println("read dir fail:", err)
return s, err
}
for _, fi := range rd {
if fi.IsDir() {
fullDir := pathname + "/" + fi.Name()
s, err = GetAllFile(fullDir, s)
if err != nil {
fmt.Println("read dir fail:", err)
return s, err
}
} else {
fullName := pathname + "/" + fi.Name()
s = append(s, fullName)
}
}
return s, nil
}
 
func main() {
// loop through and print all file names
var s[]string
s, _ = GetAllFile("/root/go/src/test", s)
 
fmt.Printf("slice: %v", s)
}

Leave a Reply

Your email address will not be published.

en_USEnglish