如何在不进入子目录的情况下迭代一个目录?

huangapple go评论67阅读模式
英文:

How to iterate a directory without entering into subdirectories

问题

假设我有以下的目录结构:

RootDir
---SubDir1
------SubSubDir
---------file1
---------file2
---SubDir2
---SubDir3
---file3
---file4

我想要遍历RootDir目录下的内容(SubDir1、Subdir2、Subdir3、file3、file4),并检查它是一个目录还是一个文件,而不进入子目录,就像filepath.Walk函数所做的那样。

Go语言库中有没有办法做到这一点?

编辑:

files, err := os.Open("c:\\Documents")
file, err := files.Readdir(0)

if err != nil {
    fmt.Printf("Error: %s\n", err)
}

for f := range file {
    fmt.Println(f.IsDir())
}

在这里,我试图遍历FileInfo,它是一个切片,并检查每个文件是否是一个目录,但我总是得到以下错误:

f.IsDir未定义(类型int没有IsDir字段或方法)
英文:

Lets say I have the following directory structure:

RootDir
---SubDir1
------SubSubDir
---------file1
---------file2
---SubDir2
---SubDir3
---file3
---file4

I want to iterate only over the contents of the RootDir(SubDir1, Subdir2, Subdir3, file3, file 4) and check if it is a dir or a file, without entering into the subdirectories, like filepath.Walk does.

Is there any way to do this in the Go library ?

edit:

files, err := os.Open("c:\\Documents")
file, err := files.Readdir(0)

if err != nil {
	fmt.Printf("Error: %s\n", err)
}

for f := range file {
	fmt.Println(f.IsDir())
}

So here I am trying to iterate trough the FileInfo, which is a slice, and check for every file if it is a directory, but I always get this error:

f.IsDir undefined (type int has no field or method IsDir)

答案1

得分: 2

你可以使用os.Open打开一个目录,并返回一个*os.File对象,该对象具有一个Readdir()方法,用于获取目录中的os.FileInfo对象,而这些FileInfo对象具有一个IsDir()方法。

英文:

You can read a directory by opening it with os.Open and the returned *os.File has a Readdir() method which gives os.FileInfos for the direct folder content and these FileInfo have an IsDir() method.

huangapple
  • 本文由 发表于 2014年1月16日 01:58:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/21144895.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定