zoukankan      html  css  js  c++  java
  • 6.5 列出当前目录所有文件

    
    package main
    
    import (
    	"fmt"
    	"io/ioutil"
    	"os"
    	"path/filepath"
    )
    
    func main() {
    
    	fmt.Println("List by ReadDir")
    	listDirByReadDir(".")
    	fmt.Println()
    	fmt.Println("List by Walk")
    	listDirByWalk(".")
    }
    
    func listDirByWalk(path string) {
    	filepath.Walk(path, func(wPath string, info os.FileInfo, err error) error {
    
    		// Walk the given dir
    		// without printing out.
    		if wPath == path {
    			return nil
    		}
    
    		// If given path is folder
    		// stop list recursively and print as folder.
    		if info.IsDir() {
    			fmt.Printf("[%s]
    ", wPath)
    			return filepath.SkipDir
    		}
    
    		// Print file name
    		if wPath != path {
    			fmt.Println(wPath)
    		}
    		return nil
    	})
    }
    
    func listDirByReadDir(path string) {
    	lst, err := ioutil.ReadDir(path)
    	if err != nil {
    		panic(err)
    	}
    	for _, val := range lst {
    		if val.IsDir() {
    			fmt.Printf("[%s]
    ", val.Name())
    		} else {
    			fmt.Println(val.Name())
    		}
    	}
    }
    
    /*
    List by ReadDir
    [.idea]
    [a]
    go_web
    sample.file
    xml.go
    
    List by Walk
    [.idea]
    [a]
    go_web
    sample.file
    xml.go
    
     */
    
    
  • 相关阅读:
    bzoj 3243: [Noi2013]向量内积
    bzoj 4818: [Sdoi2017]序列计数
    AtCoder Grand Contest 023 F
    bzoj 4573: [Zjoi2016]大森林
    bzoj 5305: [Haoi2018]苹果树
    bzoj 5298: [Cqoi2018]交错序列
    codeforces496C
    codeforces534B
    牛客小白月赛13
    codeforces605A
  • 原文地址:https://www.cnblogs.com/zrdpy/p/8635674.html
Copyright © 2011-2022 走看看