天天看點

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()判斷檔案是目錄還是非目錄檔案。