I am trying to find files in the selected directory RECURSIVE, with the extension .txt , the code of the recursive function:
func fglob(dir string, ext string) ([]string, error) { var files = []string{} var err = filepath.Walk(dir, func(path string, f os.FileInfo, err error) error { if filepath.Ext(path) == ext { files = append(files, path) } return nil }) return files, err } fglob("C:/files", ".txt"); Main code:
package main import ( "fmt" "io" "os" "path/filepath" ) func main() { var files []string var err error files, err = fglob( "C:/files/folder", fmt.Sprintf("%s", ".txt", ), ) if err != nil { fmt.Println(err) } for _, file := range files { from, err := os.Open( fmt.Sprintf("%s", file, ), ) if err != nil { fmt.Println(err) } defer from.Close() fileStat, err := from.Stat() if err != nil { fmt.Println(err) } if fileStat.Size() < 1 { continue } else if fileStat.Size() > 5000 { continue } to, err := os.OpenFile("c:/files/folder/f2/"+file, os.O_RDWR|os.O_CREATE, 0666) if err != nil { fmt.Println(err) } defer to.Close() _, err = io.Copy(to, from) if err != nil { fmt.Println(err) } } } func fglob(dir string, ext string) ([]string, error) { var files = []string{} var err = filepath.Walk(dir, func(path string, f os.FileInfo, err error) error { if filepath.Ext(path) == ext { files = append(files, path) } return nil }) return files, err } But I’m writing open C:\files\folder\f2/C:\files\folder\retr.txt: The filename, directory name, or volume label syntax is incorrect. because the name of directories and files connects together. I need to search in specific directories, not in the current one.