Go语言 之读取目录内容

package main

import (
  "fmt"
  "os"
)
func main() { path
:= "I:\\test" //以只读的方式打开目录 f, err := os.OpenFile(path, os.O_RDONLY, os.ModeDir) if err != nil { fmt.Println(err.Error()) } //延迟关闭目录 defer f.Close() fileInfo, _ := f.Readdir(-1) //操作系统指定的路径分隔符 separator := string(os.PathSeparator) for _, info := range fileInfo { //判断是否是目录 if info.IsDir() { fmt.Println(path + separator + info.Name()) readDir(path + separator + info.Name()) } else { fmt.Println("文件:" + info.Name()) } } }

func (f *File) Readdir(n int) ([]FileInfo, error)

参数:n,表读取目录的成员个数。通常传-1,表读取目录所有文件对象。

返回值:FileInfo类型的切片。其内部保存了文件名。error中保存错误信息。

type FileInfo interface {
   Name() string       // base name of the file
   Size() int64        // length in bytes for regular files; system-dependent for others
   Mode() FileMode     // file mode bits
   ModTime() time.Time // modification time
   IsDir() bool        // abbreviation for Mode().IsDir()
   Sys() interface{}   // underlying data source (can return nil)
}

得到 FileInfo类型切片后,我们可以range遍历切片元素,使用.Name()获取文件名。使用.Size()获取文件大小,使用.IsDir()判断文件是目录还是非目录文件。

posted @ 2019-07-02 14:55  样子2018  阅读(1830)  评论(0编辑  收藏  举报