当前位置:网站首页>2021-05-02: given the path of a file directory, write a function

2021-05-02: given the path of a file directory, write a function

2022-06-24 15:55:00 Fuda scaffold constructor's daily question

2021-05-02: Given the path of a file directory , Write a function to count the number of all files in this directory and return . Hidden files count , But folders don't count .

Fuda answer 2021-05-02:

1. use filepath.Walk Method .

2. Traverse with breadth first +ioutil.

The code to use golang To write . The code is as follows :

package main

import (
    "container/list"
    "fmt"
    "io/ioutil"
    "os"
    "path/filepath"
    "strings"
)

func main() {
    ret := getFileNumber1("D:\\mysetup\\gopath\\src\\sf\\newclass")
    fmt.Println("1. use filepath.Walk Method :", ret)

    ret = getFileNumber2("D:\\mysetup\\gopath\\src\\sf\\newclass")
    fmt.Println("2. Traverse with breadth first +ioutil:", ret)
}

func getFileNumber1(folderPath string) int {
    folderPath = toLinux(folderPath)

    info, err := os.Lstat(folderPath)
    // Not a file , It's not a folder either 
    if err != nil {
        return 0
    }
    // If it's a file 
    if !info.IsDir() {
        return 1
    }

    // If it's a folder 
    ans := 0
    filepath.Walk(folderPath, func(path string, info os.FileInfo, err error) error {
        if info.IsDir() {
            return nil
        }
        ans++
        return nil
    })

    // Return results 
    return ans
}

func getFileNumber2(folderPath string) int {
    folderPath = toLinux(folderPath)

    info, err := os.Lstat(folderPath)
    // Not a file , It's not a folder either 
    if err != nil {
        return 0
    }
    // If it's a file 
    if !info.IsDir() {
        return 1
    }

    // Add folder to queue 
    ans := 0
    queue := list.New()
    queue.PushBack(folderPath)
    for queue.Len() > 0 {
        files, _ := ioutil.ReadDir(queue.Front().Value.(string))
        for _, file := range files {
            if file.IsDir() {
                queue.PushBack(filepath.Join(folderPath, file.Name()))
            } else {
                ans++
            }
        }
        queue.Remove(queue.Front())
    }

    // Return results 
    return ans
}

func toLinux(basePath string) string {
    return strings.ReplaceAll(basePath, "\\", "/")
}

The results are as follows :

picture

***

Zuo Shen java Code

原网站

版权声明
本文为[Fuda scaffold constructor's daily question]所创,转载请带上原文链接,感谢
https://yzsam.com/2021/05/20210504233532313f.html