dongyukang7006 2015-03-30 00:46
浏览 18
已采纳

GoLang字符串与Slices的比较

I'm able to get a list of files and folders from a directory, I've written a function called isDir to return True if the path is a directory.

Now my problem is that I want to make sure that none of the folders listed match a list of strings in a slice. The code I have might skip the first match but it will print out everything else anyways. I need to process the folders that aren't to be avoided.

Code is for Windows 7/8 directories but I should be able to get a Linux sample working too should one be provided.

package main

import (
    "fmt"
    "io/ioutil"
    "os"
    "strings"
)

func isDir(pth string) (bool) {
         fi, err := os.Stat(pth)
         if err != nil {
                 return false
         }
         return fi.Mode().IsDir()
}

func main() {
    gcomputer := "localhost"
    location := fmt.Sprintf("\\\\%s\\c$\\Users\\", gcomputer)
    // Profiles to avoid
    avoid := []string{"Administrator", "Default", "Public"}
    // walk through files & folders in the directory (location) & return valid profiles
    files, _ := ioutil.ReadDir(location)
    for _, f := range files {
        fdir := []string{location, f.Name()}
        dpath := strings.Join(fdir, "")

        if isDir(dpath) {
            for _, iavoid := range avoid {
                for iavoid != f.Name() {
                    fmt.Println(dpath)
                    break
                }
                break
            }
        }
    }
}

I don't mind using a third-party module, I've been working on this too long and starting to lose my cool, making understanding the docs a bit difficult. Any tips would be appreciated. Thank you.

  • 写回答

2条回答 默认 最新

  • dq8081 2015-03-30 01:29
    关注

    For example,

    package main
    
    import (
        "fmt"
        "io/ioutil"
    )
    
    func avoid(name string) bool {
        profiles := []string{"Administrator", "Default", "Public"}
        for _, p := range profiles {
            if name == p {
                return true
            }
        }
        return false
    }
    
    func main() {
        gcomputer := "localhost"
        location := fmt.Sprintf("\\\\%s\\c$\\Users\\", gcomputer)
        files, err := ioutil.ReadDir(location)
        if err != nil {
            fmt.Println(err)
            return
        }
        for _, f := range files {
            if f.IsDir() && !avoid(f.Name()) {
                dpath := location + f.Name()
                fmt.Println(dpath)
            }
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?