当前位置: 首页>>代码示例>>Golang>>正文


Golang File.Readdir方法代码示例

本文整理汇总了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,
		})
	}
}
开发者ID:jayvansantos,项目名称:http-watcher,代码行数:25,代码来源:http-watcher.go

示例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
}
开发者ID:jdp,项目名称:gopher-server,代码行数:31,代码来源:gopher.go

示例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)
}
开发者ID:shitfSign,项目名称:gohttpd,代码行数:28,代码来源:main.go

示例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
}
开发者ID:last-time,项目名称:della,代码行数:26,代码来源:dm_src_provider.go

示例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
}
开发者ID:daozhao,项目名称:s3weed,代码行数:28,代码来源:utils.go

示例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
}
开发者ID:geeksteam,项目名称:DiskAnalyzer,代码行数:36,代码来源:diskanalyzer.go

示例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
}
开发者ID:hartzler,项目名称:scas,代码行数:29,代码来源:scas.go

示例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
}
开发者ID:GarX,项目名称:go-pac,代码行数:31,代码来源:worker.go

示例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
}
开发者ID:YijinLiu,项目名称:usongs,代码行数:25,代码来源:song_file.go

示例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
}
开发者ID:hartzler,项目名称:scas,代码行数:29,代码来源:scas.go

示例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
}
开发者ID:saltmueller,项目名称:skia-buildbot,代码行数:8,代码来源:fileutil.go

示例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()
		}
	}
}
开发者ID:hyl87,项目名称:2011_Go_Geo_Gfx,代码行数:27,代码来源:gorun.go

示例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 + "&nbsp;<span class=\"comment\">" + sizeStr + "[" + fi.ModTime().Format("2006-01-02 03:04") + "]</span></div>"
	}

	render(w, data)
}
开发者ID:devtoby,项目名称:gofs,代码行数:26,代码来源:func.go

示例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,
	})
}
开发者ID:itang,项目名称:gohttp,代码行数:26,代码来源:fileserver.go

示例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
}
开发者ID:hopkinsth,项目名称:lambda-phage,代码行数:61,代码来源:zip.go


注:本文中的os.File.Readdir方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。