golang get all files in a directory

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() {
			fullName := pathname + "/" + fi.Name()
			s = append(s, fullName)
		}
	}
	return s, nil
}
 
func main(){
    var s []string
    s, _ = GetAllFile(".", s)
}

Get all files in the current project root directory (including files in folders)

func GetFiles(folder string){
	files, _ := ioutil.ReadDir(folder)
	for _,file := range files{
		if file.IsDir(){
			GetFiles(folder + "/" + file.Name())
		}else{
			fmt.Println(folder + "/" + file.Name())
		}
	}
 
}
 
func main() {
    GetFiles(".")
}

Leave a Reply

Your email address will not be published.

en_USEnglish