The Go language scans directories and retrieves relevant information
- 2020-05-17 05:40:44
- OfStack
This example shows how the Go language can scan a directory and get relevant information. Share with you for your reference. The specific analysis is as follows:
Preface: recently I saw that Go has an func in it that can easily scan the entire directory and get the corresponding directory and file information, so I packaged it and got all the information of file info so that I could easily do other things.
Go directly to the code, which is based on Go version 1
package main
import (
"path/filepath"
"os"
"flag"
"fmt"
"time"
)
const (
IsDirectory = iota
IsRegular
IsSymlink
)
type sysFile struct {
fType int
fName string
fLink string
fSize int64
fMtime time.Time
fPerm os.FileMode
}
type F struct {
files []*sysFile
}
func (self *F) visit(path string, f os.FileInfo, err error) error {
if ( f == nil ) {
return err
}
var tp int
if f.IsDir() {
tp = IsDirectory
}else if ( f.Mode() & os.ModeSymlink ) > 0 {
tp = IsSymlink
}else{
tp = IsRegular
}
inoFile := &sysFile{
fName : path,
fType : tp,
fPerm : f.Mode(),
fMtime: f.ModTime(),
fSize : f.Size(),
}
self.files = append( self.files, inoFile )
return nil
}
func main() {
flag.Parse()
root := flag.Arg(0)
self := F{
files: make( []*sysFile, 0 ),
}
err := filepath.Walk(root, func(path string, f os.FileInfo, err error) error {
return self.visit(path, f, err)
})
if err != nil {
fmt.Printf("filepath.Walk() returned %v\n", err)
}
for _, v := range self.files {
fmt.Println( v.fName,v.fSize )
}
}
I hope this article has helped you with the programming of Go language.