Home > database >  Find particular file in a root directory in golang?
Find particular file in a root directory in golang?

Time:01-03

I have a below code which finds a particular file passed as an input parameter recursively in a root directory which contains sub directories too and then it returns the full path of that file.

func findFile(root string, fileName string) ([]string, error) {
    var files []string
    err := filepath.WalkDir(root, func(path string, d fs.DirEntry, err error) error {
        if !d.IsDir() && d.Name() == fileName {
            files = append(files, path)
        }
        return nil
    })
    return files, err
}

This is how I use it -

findFile("/home", "abc.json")

It works fine but now I need to do one more thing. Instead of passing full complete fileName, I should also be able to pass something like this prefix-*.json which means find me all the files which starts with prefix- and ends with .json file type. Is there any way by which above method can be modified to work with both the cases? If not then what is the better way to do this?

I should be able to do below things and it will return me path of all those files matched.

findFile("/home", "abc.json")
findFile("/home", "prefix-*.json")

Update

I got it working with below code -

func findFile(root string, fileName string) ([]string, error) {
    var files []string
    err := filepath.WalkDir(root, func(pathh string, d fs.DirEntry, err error) error {
        if !d.IsDir() {
            if ok, err := path.Match(fileName, d.Name()); ok && err == nil {
                files = append(files, pathh)
            }
        }
        return nil
    })
    return files, err
}

Let me know if it looks good. Also anything I can simplify in my above code as I got two separate if conditions one by one. Can they be combined in one if condition?

CodePudding user response:

as I got two separate if conditions one by one. Can they be combined in one if condition?

No: keeping those conditions separate is clearer.

And since ryanuber/go-glob is meant to compare two arbitrary strings, path.Match(fileName, d.Name()) is enough in your case, since you are comparing paths.

  •  Tags:  
  • go
  • Related