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