go 遍历文件中中的所有文件打印
作者:互联网
package main
import (
"fmt"
"io"
"os"
"strings"
)
type fileFilter func(fpath string) bool
type callBack func(path string)
func ReadFile(path string) {
file, err := os.Open(path)
if err != nil {
return
}
content := make([]byte, 1024)
contentAll := make([]byte, 1024)
for {
n, err := file.Read(content)
if err == io.EOF {
break
}
contentAll = append(contentAll, content[:n]...)
fmt.Println(contentAll[:n])
}
fmt.Println(string(contentAll))
}
func Dir(path string, filter fileFilter, back callBack) {
file, err := os.Open(path)
//fmt.Println(file)
if err != nil {
fmt.Println(err)
return
}
defer file.Close()
dirName, err := file.Readdirnames(-1) //-1表示读取全部没有限制
for _, name := range dirName {
//fmt.Println(dirName)
fPath := path + "/" + name
if fileInfo, err := os.Stat(fPath); err == nil {
if fileInfo.IsDir() {
//fmt.Println(fPath)
Dir(fPath, filter, back)
}
if filter == nil || filter(fPath) {
//fmt.Printf("file:%#v", fPath)
if back != nil {
back(fPath)
}
}
}
}
}
func main() {
Dir("folder", func(path string) bool {
return strings.HasSuffix(path, ".go")
}, func(path string) {
ReadFile(path)
})
}
标签:文件,string,err,中中,fmt,fPath,file,go,path 来源: https://www.cnblogs.com/wangsk/p/15861291.html