-1

I'm making a function like ioutil.ReadDir() but recursively due I want all the files in folders and subfolders and ioutil.ReadDir() just do it in the specified folder but I don't know how to append items to an array of []os.FileInfo that I've created.

This is what I have:

func GetFilesRecursively(searchDirectory string) (foundFileList []os.FileInfo, errorGenerated error){

   fileList := []os.FileInfo{}
   allFilesAndFolders := []string{}

   //Get all the files and directories
   err := filepath.Walk(searchDirectory, func(path string, f os.FileInfo, err error) error {
       allFilesAndFolders = append(allFilesAndFolders, path)
       return nil
   })

   // Remove directories due those are also added into the array and we don't need them
   for _, file := range allFilesAndFolders{

       fileInfo, _ := os.Stat(file)

       if (!fileInfo.Mode().IsDir()){
          fileList = append(fileList, file) //error here!!
       }
   }

   return fileList, err
}

The error is in the comments in the code snippet above

How could I do that?

Javier Salas
  • 1,064
  • 5
  • 15
  • 38

1 Answers1

1

You try to append a string to an array of os.FileInfo. That is a type error.

Here is a version of your code that does what you want and looks more Go-like, with shorter variable names, unnamed return types (their types perfectly decribe what they do) and using var to create an empty slice.

func GetFilesRecursively(root string) ([]os.FileInfo, error) {
    var files []os.FileInfo

    // walk all directories but only collect files
    err := filepath.Walk(root, func(path string, f os.FileInfo, err error) error {
        if !f.IsDir() {
            files = append(files, f)
        }
        return nil
    })

    return files, err
}
gonutz
  • 5,087
  • 3
  • 22
  • 40