i need some help in golan to write a program that can search through a given directory and its subdirectories to look for a particular word word in each of them.
this what i have so far to list the directories and save them as an array. now i want to check each of them to see if it has children, if yes, i should open it until i reach the last level of the tree.
package main
import (
"fmt"
"os"
)
func main() {
d, err := os.Open("/Perkins")
// fmt.Println(d.Readdirnames(-1))
y, err:=d.Readdirnames(-1) //
fmt.Println(y)
for i:=0; i<len(y); i++{
if y[i]!=" "{
Folders:=y[i]
temp,err:=os.Open("/"Folders) //how do i out the array element as a path?
fmt.Println (temp)
fmt.Println(err)
}
}
Note: "/"Folders
wouldn't work: "/" + Folders
In your case, this should work better:
temp,err:=os.Open("/Perkins/" + Folders)
(even though 'Folders
' is not a good name, 'subfolder
' would be more appropriate)
A more efficient way, as commented by chendesheng (see answer), would be (as in this class) to use path/filepath/#Walk
:
package main
import (
"fmt"
"os"
"path/filepath"
)
func main() {
filepath.Walk("/Perkins", func(path string, info os.FileInfo, err error) error {
fmt.Println(path)
return nil
})
}
That will list all the file, but you can associate it with a function which will filter those: see this example:
matched, err := filepath.Match("*.mp3", fi.Name())
You can then ignore the files you don't want and proceed only for the ones matching your pattern.
Maybe you need this? http://golang.org/pkg/io/ioutil/#ReadDir And then check is type from http://golang.org/pkg/os/#FileInfo and do recursive func if it folder
I think you can use filepath.Walk
Walk walks the file tree rooted at root, calling walkFn for each file or directory in the tree, including root. All errors that arise visiting files and directories are filtered by walkFn. The files are walked in lexical order, which makes the output deterministic but means that for very large directories Walk can be inefficient. Walk does not follow symbolic links.