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.
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)
}
}
}
If your list of strings to avoid gets bigger, you might not want to be iterating over them for every directory. Might I suggest a small modification to @peterSO's answer:
package main
import (
"fmt"
"io/ioutil"
)
var avoidanceSet = map[string]bool{
"Administrator": true,
"Default": true,
"Public": true,
}
func avoid(name string) bool {
_, inSet := avoidanceSet[name]
return inSet
}
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)
}
}
}