Golang 目錄檔案數量和大小統計

來源:互聯網
上載者:User
這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。

《The Go Programming Language》筆記

import (    "flag"    "fmt"    "io/ioutil"    "os"    "path/filepath"    "sync"    "time")//擷取目錄dir下的檔案大小func walkDir(dir string, wg *sync.WaitGroup, fileSizes chan<- int64) {    defer wg.Done()    for _, entry := range dirents(dir) {        if entry.IsDir() {//目錄            wg.Add(1)            subDir := filepath.Join(dir, entry.Name())            go walkDir(subDir, wg, fileSizes)        } else {            fileSizes <- entry.Size()        }    }}//sema is a counting semaphore for limiting concurrency in direntsvar sema = make(chan struct{}, 20)//讀取目錄dir下的檔案資訊func dirents(dir string) []os.FileInfo {    sema <- struct{}{}    defer func() { <-sema }()    entries, err := ioutil.ReadDir(dir)    if err != nil {        fmt.Fprintf(os.Stderr, "du: %v\n", err)        return nil    }    return entries}//輸出檔案數量的大小func printDiskUsage(nfiles, nbytes int64) {    fmt.Printf("%d files %.1f GB\n", nfiles, float64(nbytes)/1e9)}//提供-v 參數會顯示程式進度資訊var verbose = flag.Bool("v", false, "show verbose progress messages")func Start() {    flag.Parse()    roots := flag.Args()//需要統計的目錄    if len(roots) == 0 {        roots = []string{"."}    }    fileSizes := make(chan int64)    var wg sync.WaitGroup    for _, root := range roots {        wg.Add(1)        go walkDir(root, &wg, fileSizes)    }    go func() {        wg.Wait() //等待goroutine結束        close(fileSizes)    }()    var tick <-chan time.Time    if *verbose {        tick = time.Tick(100 * time.Millisecond) //輸出時間間隔    }    var nfiles, nbytes int64loop:    for {        select {        case size, ok := <-fileSizes:            if !ok {                break loop            }            nfiles++            nbytes += size        case <-tick:            printDiskUsage(nfiles, nbytes)        }    }    printDiskUsage(nfiles, nbytes)}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.