本文整理汇总了Golang中os.File.Readdir方法的典型用法代码示例。如果您正苦于以下问题:Golang File.Readdir方法的具体用法?Golang File.Readdir怎么用?Golang File.Readdir使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类os.File
的用法示例。
在下文中一共展示了File.Readdir方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: dirList
func dirList(w http.ResponseWriter, f *os.File) {
w.Header().Set("Content-Type", "text/html; charset=utf-8")
if dirs, err := f.Readdir(-1); err == nil {
files := make([]map[string]string, len(dirs)+1)
files[0] = map[string]string{
"name": "..", "href": "..", "size": "-", "mtime": "-",
}
for i, d := range dirs {
href := d.Name()
if d.IsDir() {
href += "/"
}
files[i+1] = map[string]string{
"name": d.Name(),
"href": href,
"size": formatSize(d),
"mtime": d.ModTime().Format("2006-01-02 15:04:05"),
}
}
reloadCfg.dirListTmpl.Execute(w, map[string]interface{}{
"dir": f.Name(),
"files": files,
})
}
}
示例2: Directory
// Directory sends a Gopher listing of the directory specified
// If a gophermap file is present, it is used instead of listing the directory contents
func (s *Server) Directory(ctx *Context, dir *os.File) (ok bool, err os.Error) {
cwd := dir.Name()[len(s.Cwd):]
if mapfile, maperr := os.Open(dir.Name()+"/gophermap", 0, 0); maperr == nil {
defer mapfile.Close()
s.Gophermap(ctx, mapfile, dir)
ok = true
} else {
entries, err := dir.Readdir(-1)
if err != nil {
s.Logger.Printf("Could not show directory: `%s'\n", err)
return
}
for _, entry := range entries {
expandedName := strings.Trim(fmt.Sprintf("%s/%s", cwd, entry.Name), "/")
switch true {
case entry.IsRegular():
_, err = ctx.Write(s.TextfileLine(entry.Name, expandedName))
case entry.IsDirectory():
_, err = ctx.Write(s.DirectoryLine(entry.Name, expandedName))
default:
_, err = ctx.Write(s.InfoLine(entry.Name))
}
}
s.Logger.Printf("Served directory `%s'\n", cwd)
ctx.Write(".")
ok = true
}
return
}
示例3: writeFilelist
func writeFilelist(w http.ResponseWriter, f *os.File, run bool) {
files, err := f.Readdir(0)
if err != nil {
fmt.Fprintf(w, "404")
return
}
fileInfos := []*FileInfo{}
for _, file := range files {
fileName := file.Name()
fileSize := file.Size()
if file.IsDir() {
fileName += "/"
}
url := fileName
if run {
url += "?run=1"
}
fileInfos = append(fileInfos, &FileInfo{Name: fileName, Url: url, Size: fileSize})
}
if run {
StatGet(fileInfos)
err = tmpl2.Execute(w, fileInfos)
} else {
err = tmpl.Execute(w, fileInfos)
}
checkErr(err)
}
示例4: getFileList
func (p *DmSrcProvider) getFileList(path string) ([]string, error) {
var err error
var f *os.File
var fileNameArr []string
if f, err = os.Open(path); err != nil {
return fileNameArr, err
}
defer f.Close()
fileInfoArr, err := f.Readdir(-1)
if err != nil {
return fileNameArr, err
}
for _, fileInfo := range fileInfoArr {
if fileInfo.Name() == "." || fileInfo.Name() == ".." {
continue
}
if fileInfo.IsDir() || strings.TrimSpace(fileInfo.Name()) == "" {
continue
}
fileNameArr = append(fileNameArr, fileInfo.Name())
}
sort.Strings(fileNameArr)
return fileNameArr, nil
}
示例5: MapDirItems
// MapDirItems calls todo for every item in dir for which check returns true
func MapDirItems(dir string, check func(os.FileInfo) bool, todo func(os.FileInfo) error) (err error) {
var (
dh *os.File
fi os.FileInfo
fis []os.FileInfo
)
if dh, err = os.Open(dir); err != nil {
return
}
defer dh.Close()
for {
if fis, err = dh.Readdir(1000); err != nil {
if err == io.EOF {
break
}
return
}
for _, fi = range fis {
if check(fi) {
if err = todo(fi); err != nil {
return
}
}
}
}
return nil
}
示例6: GetDirectoryStructureWithDepth
// GetDirectoryStructureWithDepth returns hierarchical representation of os's directories with given depth,
// as well as their sizes.
func GetDirectoryStructureWithDepth(fullpath string, depth int) (result Directory, err error) {
var fileSize int64
if fileSize, err = GetFullDirSize(fullpath); err != nil {
return
}
var currentDir *os.File
defer currentDir.Close()
if currentDir, err = os.Open(fullpath); err != nil {
return
}
var files []os.FileInfo
if files, err = currentDir.Readdir(0); err != nil {
return
}
var directories []Directory
for _, v := range files {
if v.IsDir() && depth > 0 {
var subDir Directory
subDirPath := path.Join(fullpath, v.Name())
if subDir, err = GetDirectoryStructureWithDepth(subDirPath, depth-1); err == nil {
directories = append(directories, subDir)
} else {
return
}
}
}
result = Directory{fullpath, fileSize, directories}
return result, nil
}
示例7: init_tx
func init_tx(f *os.File) error {
tx = newTxLog()
infos, err := f.Readdir(1024)
if err != nil {
fmt.Println(err)
panic("error initializing scas")
}
log.Println("checking for old tx logs to replay...")
for _, info := range infos {
name := info.Name()
if strings.HasPrefix(name, LOGPREFIX) && name != tx.file.Name() {
log.Println("replaying tx log: ", name)
fullpath := path.Join(txdir, name)
oldfile, err := os.Open(fullpath)
err = tx.replay(oldfile, func(k *Key, v Value) error {
log.Println("recovering key / value:", k, v)
return Put(k, v)
})
oldfile.Close()
err = os.Remove(fullpath)
if err != nil {
fmt.Println("error removing old tx file!", err)
// continue on for now... will keep getting replayed at startup.
}
log.Println("tx log replay complete.")
}
}
return nil
}
示例8: findRecursively
// find the directories and files which matches the regular expression
func findRecursively(dir *os.File, reg *regexp.Regexp, currentwd string) (dirs, files []string) {
dirs = make([]string, 0)
files = make([]string, 0)
fileInfos, err := dir.Readdir(0)
if err != nil {
return
}
for i := 0; i < len(fileInfos); i++ {
name := fileInfos[i].Name()
if reg.Match([]byte(name)) == true {
if fileInfos[i].IsDir() == true {
dirs = append(dirs, currentwd+"/"+name)
} else {
files = append(dirs, currentwd+"/"+name)
}
}
if fileInfos[i].IsDir() == true {
redir, err := os.Open(currentwd + "/" + name)
if err != nil {
continue
}
newDirs, newFiles := findRecursively(redir, reg, currentwd+"/"+name)
dirs = append(dirs, newDirs...)
files = append(files, newFiles...)
redir.Close()
}
}
return
}
示例9: ListMp3Files
func ListMp3Files(f *os.File, sfl []*SongFile) []*SongFile {
fi, err := f.Stat()
if err != nil {
log.Fatal(err)
}
if fi.Mode().IsDir() {
fis, err := f.Readdir(0)
if err != nil {
log.Fatal(err)
}
for _, fi := range fis {
name := filepath.Join(f.Name(), fi.Name())
if f, err := os.Open(name); err != nil {
log.Printf("Failed to open '%s': %v", name, err)
} else {
sfl = ListMp3Files(f, sfl)
}
}
} else if fi.Mode().IsRegular() {
if strings.ToLower(filepath.Ext(f.Name())) == ".mp3" {
sfl = append(sfl, NewSongFile(f.Name(), fi.Size()))
}
}
return sfl
}
示例10: init_ss
func init_ss(f *os.File) error {
infos, err := f.Readdir(1024)
if err != nil {
fmt.Println(err)
panic("error initializing scas")
}
log.Println("loading sstables...")
for _, info := range infos {
if strings.HasPrefix(info.Name(), SSDATA_PREFIX) {
log.Println("loading sstable: ", info.Name())
datafile, err := os.Open(path.Join(ssdir, info.Name()))
if err != nil {
return err
}
ss, err := newSSTable(datafile)
if err != nil {
return err
}
err = ss.readIndex()
if err != nil {
fmt.Println("error loading sstable!", err)
// continue on for now... will keep getting replayed at startup.
}
sstables = append(sstables, *ss)
}
}
log.Println("loading sstables complete.")
return nil
}
示例11: MustReaddir
// MustReaddir returns a slice of os.FileInfo for every file in the given dir. This is equivilent to calling dir.Readdir(-1), except this call will stop the program on an error
func MustReaddir(dir *os.File) []os.FileInfo {
fi, err := dir.Readdir(-1)
if err != nil {
glog.Fatal(err)
}
return fi
}
示例12: ensureFolderHierarchy
func ensureFolderHierarchy(srcDir *os.File, targetDirPath string) {
var fileInfos, err = srcDir.Readdir(0)
var srcSubDir, targetSubDir *os.File
var srcDirPath, subDirName, subDirPath string
if err != nil {
panic(err)
}
for _, fileInfo := range fileInfos {
if fileInfo.IsDir() {
srcDirPath = srcDir.Name()
subDirName = fileInfo.Name()
if srcSubDir, err = os.Open(path.Join(srcDirPath, subDirName)); err != nil {
panic(err)
}
subDirPath = path.Join(targetDirPath, subDirName)
if targetSubDir, err = os.Open(subDirPath); err != nil {
if err = os.Mkdir(subDirPath, os.ModeDir|os.ModePerm); err != nil {
panic(err)
}
} else {
targetSubDir.Close()
}
ensureFolderHierarchy(srcSubDir, subDirPath)
srcSubDir.Close()
}
}
}
示例13: dirServ
func dirServ(w http.ResponseWriter, oFile *os.File, p string) {
w.Header().Set("Content-Type", "text/html;charset=utf-8")
data := make(map[string]string)
data["title"] = "目录查看"
data["head"] = "<strong>当前位置:</strong> " + getPathLink(p)
fiList, _ := oFile.Readdir(-1)
if len(fiList) == 0 {
data["content"] = "<i><空目录></i>"
}
for _, fi := range fiList {
linkStr := fi.Name()
var sizeStr, target = "", ""
if fi.IsDir() {
linkStr += "/"
} else {
target = " target=\"_blank\""
sizeStr = "[" + getFileSize(fi.Size()) + "] "
}
linkStr = "<a href=\"" + linkStr + "\"" + target + ">" + linkStr + "</a>"
data["content"] += "<div>" + linkStr + " <span class=\"comment\">" + sizeStr + "[" + fi.ModTime().Format("2006-01-02 03:04") + "]</span></div>"
}
render(w, data)
}
示例14: processDir
func (_ *FileServer) processDir(w http.ResponseWriter, dir *os.File, fullpath string, relpath string) {
w.Header().Set("Content-type", "text/html; charset=UTF-8")
fis, err := dir.Readdir(-1)
gotang.AssertNoError(err, "读取文件夹信息出错!")
items := make([]Item, 0, len(fis))
for _, fi := range fis {
var size int64 = 0
if !fi.IsDir() {
size = fi.Size()
}
item := Item{
Name: fi.Name(),
Title: fi.Name(),
URI: path.Join(relpath, fi.Name()),
Size: size,
}
items = append(items, item)
}
tmp.Execute(w, map[string]interface{}{
"ParentURI": path.Dir(relpath),
"CurrentURI": relpath,
"files": items,
})
}
示例15: AddDirectory
// adds a directory recursively
func (z *zipFile) AddDirectory(f *os.File, infoCh chan<- string) error {
debug := debug.Debug("zipFile.AddDirectory")
dirName := f.Name()
debug("adding directory %s", dirName)
fi, err := f.Readdir(-1)
if err != nil {
return err
}
for _, info := range fi {
debug("zname is...", z.f.Name())
fName := info.Name()
fullName := dirName + "/" + fName
if info.IsDir() {
if strings.Index(fName, ".") != 0 {
debug("found directory, adding file %s", dirName+"/"+fName)
if infoCh != nil {
infoCh <- fmt.Sprintf("adding %s", fullName)
}
f, err := os.Open(fullName)
if err != nil {
// TODO: prob don't want to do this ALWAYS
return err
}
err = z.AddDirectory(f, infoCh)
if err != nil {
return err
}
err = f.Close()
if err != nil {
return err
}
}
} else if info.Name() != z.fName {
debug("have file %s in directory %s, adding now", info.Name(), dirName)
if infoCh != nil {
infoCh <- fmt.Sprintf("adding %s", fullName)
}
_, err := z.AddFile(dirName + "/" + info.Name())
if err != nil {
// TODO: prob don't want to do this ALWAYS
return err
}
}
}
return nil
}