Created
June 19, 2018 08:49
-
-
Save wanghongfei/69d2c1eca65432a40af1d63b46e1938b to your computer and use it in GitHub Desktop.
递归遍历当前目录,删除指定文件
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"path/filepath" | |
"os" | |
"fmt" | |
) | |
func main() { | |
dir, err := filepath.Abs(filepath.Dir(os.Args[0])) | |
if nil != err { | |
fmt.Println(err) | |
return | |
} | |
fmt.Printf("working dir: %s\n", dir) | |
target := "target" | |
if len(os.Args) > 1 { | |
target = os.Args[1] | |
} | |
fmt.Printf("recursively delete: %s\n", target) | |
fileList, err := traverseFile(dir, target) | |
if nil != err { | |
fmt.Println(err) | |
return | |
} | |
succ, failed := delAll(fileList) | |
fmt.Printf("success = %d, failed = %d\n", succ, failed) | |
} | |
func traverseFile(dir string, target string) ([]string, error) { | |
fileList := make([]string, 0, 30) | |
err := filepath.Walk(dir, func(path string, info os.FileInfo, err error) error { | |
if info == nil { | |
return err | |
} | |
if info.Name() == target { | |
fileList = append(fileList, path) | |
} | |
return nil | |
}) | |
return fileList, err | |
} | |
func delAll(fileList []string) (int, int) { | |
if len(fileList) == 0 { | |
return 0, 0 | |
} | |
succ := 0 | |
failed := 0 | |
for _, f := range fileList { | |
err := os.RemoveAll(f) | |
if nil != err { | |
failed++ | |
} else { | |
succ++ | |
fmt.Println("deleted: " + f) | |
} | |
} | |
return succ, failed | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment