Golang study notes–traverse all files in folders and subfolders

To traverse all files in a folder and subfolders, the easiest way to think of is to use a recursive method, first visit the current directory, read all files in the current directory, if it is a directory, recursively call to traverse all files in the directory. The specific code is as follows:

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. Required fields are marked *

en_USEnglish