Fairly new at go. I am trying to basically read all the files in directory and subdirectory, populate in a slice and then process further. Here is the code (Main functions to look are Main and expandDirectory
package main
import (
"fmt"
"io/ioutil"
"os"
)
const dirname string = "MyDirectory"
func check(e error) {
if e != nil {
panic(e)
}
}
func expandDirectory(currentDirectory string, allFiles []os.FileInfo) []os.FileInfo {
files, e := ioutil.ReadDir(currentDirectory)
check(e)
for _, internalDir := range files {
switch mode := internalDir.Mode(); {
case mode.IsDir():
var filepath = currentDirectory + internalDir.Name() + "\\"
expandDirectory(filepath, allFiles)
case mode.IsRegular():
allFiles = append(allFiles, internalDir)
}
}
return allFiles
}
func main() {
allFiles := expandDirectory(dirname, make([]os.FileInfo, 5))
fmt.Printf("%v", cap(allFiles))
}
The final print will print 5 which is the initial value.
Just FYI, the expandDirectory function is just recursive function in case of directories and adding the file reference in case of a file.
Thanks for the help
Where am I going wrong
FINAL CODE (changes Only)
func main() {
allFiles := expandDirectory(dirname)
}
func expandDirectory(currentDirectory string) []os.FileInfo {
allFiles := make([]os.FileInfo, 0, 5)
....
case mode.IsDir():
....
allFiles = append(allFiles, expandDirectory(filepath)...)
....
return allFiles
}
You need to append the result to it:
allFiles = append(allFiles, expandDirectory(filepath, allFiles)...)
Also
allFiles := expandDirectory(dirname, make([]os.FileInfo, 5))
should be:
allFiles := expandDirectory(dirname, make([]os.FileInfo, 0, 5))
Otherwise you will be appending to allFiles and the first 5 items will be empty.