Which pkg can list all files under a directory?

27 views
Skip to first unread message

aXe

unread,
Jan 31, 2013, 9:31:29 PM1/31/13
to golang...@googlegroups.com, golan...@googlegroups.com

I want to get all the file names in a directory, not including the sub-dir and the files in sub-dir. I don’t want use finepath.Walk. Any other pkg has such a functionality?

 

Br

aXe

shine

unread,
Jan 31, 2013, 10:34:24 PM1/31/13
to golang...@googlegroups.com, golan...@googlegroups.com

You can try the following code:


package main


import (

"log"

"os"

)


func main() {

dir, err := os.Open("/Users/apple")

checkErr(err)

defer dir.Close()


fi, err := dir.Stat()

checkErr(err)


filenames := make([]string, 0)

if fi.IsDir() {

fis, err := dir.Readdir(-1) // -1 means return all the FileInfos

checkErr(err)


for _, fileinfo := range fis {

if !fileinfo.IsDir() {

filenames = append(filenames, fileinfo.Name())

}

}

}


log.Println("Files: ", filenames)

}


func checkErr(err error) {

if err != nil {

log.Fatal(err)

}

}


在 2013年2月1日星期五UTC+8上午10时31分29秒,axe写道:

aXe

unread,
Jan 31, 2013, 10:38:51 PM1/31/13
to golang...@googlegroups.com, golan...@googlegroups.com

Glad to see a new method. J

--
--
官网: http://golang-china.org/
IRC: irc.freenode.net #golang-china
@golangchina
 
---
您收到此邮件是因为您订阅了 Google 网上论坛的“Golang-China”论坛。
要退订此论坛并停止接收此论坛的电子邮件,请发送电子邮件到 golang-china...@googlegroups.com
要查看更多选项,请访问 https://groups.google.com/groups/opt_out
 
 

Reply all
Reply to author
Forward
0 new messages