Teach you step by step how to develop a simple directory generator using Go language

Release: 2023-07-25 16:55:53
forward
809 people have browsed it

Preface

Sometimes, I look at my directory, or I want to find a file, especially It’s always a little uncomfortable when there are many directories.

Teach you step by step how to develop a simple directory generator using Go language

For example, this directory is one of my tutorial directories.

But I can’tknow at a glance# of each folder #There is everything, and it is very troublesome to find a file every time.

So, based on the above requirements, using the Go language, I finally made a directory generator, which feels good.

The effect achieved

通过编写的脚本,可以将目录整合成.txt文件,并且下级目录使用4个空格缩进。

代码

先别管怎么实现的,先看代码。

package main


import (
    "bytes"
    "flag"
    "fmt"
    "io/ioutil"
    "os"
    "path/filepath"
)


func GenderNSymbol(char byte, count int) string {
    symbolSince := bytes.Repeat([]byte{char}, count)
    var symbol = string(symbolSince)
    return symbol
}


// @title    GenderDirTree
// @description   生成目录树
// @param     path        string         "需要生成的目录"
// @param     count        int           "生成相同字符的个数"
// @param     char        byte           "生成相同字符的字符"
// @param     current_tier        int            "当前层数"
// @param     end_tier        int            "终止层数"
// @param     fileObj        int            "文件对象"
// @return    无        无         "无"
func GenderDirTree(path string, count int, char byte, current_tier int, end_tier int, fileObj *os.File) {
    if !(current_tier < end_tier) && end_tier != 0 {
        return
}
    current_tier++
    files, err := ioutil.ReadDir(path)
    if err != nil {
        fmt.Println("错误:目录错误")
        return
}
    for _, file := range files {
        var name = file.Name()
        //生成指定数目的相同符号
        var plac = GenderNSymbol(char, count)
        //符号+目录
        var sname = fmt.Sprintf("%s%s\n", plac, name)
        //输出当前目录
        fileObj.WriteString(sname)
        //fmt.Println(sname)
        //判断是否为目录,如果是,继续下次递归
        var isDir = file.IsDir()
        if isDir {
            //拼接传入的目录和循环的当前目录
            var nerPaht = filepath.Join(path, name)
            GenderDirTree(nerPaht, count+4, char, current_tier, end_tier, fileObj)
        }
}
}


func main() {
    //终止层数,0表示无限层,>0表示指定层数
    var end_tier int
    //输入的目录
    //var path = `D:\0_教程\易锦教程`
    var path string
    flag.StringVar(&path, "path", "", "目录")
    flag.IntVar(&end_tier, "tier", 0, "终止层数")
    flag.Parse()
    //文件对象
    var wDirPath = filepath.Join(path, "目录.txt")
    fileObj, _ := os.OpenFile(wDirPath, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0666)
    defer fileObj.Close()
    //生成目录树
    GenderDirTree(path, 0, &#39; &#39;, 0, end_tier, fileObj)
}
Copy after login

去掉注释,其实也就30行代码,就实现了这个功能。

实现的功能

  • 自定义要生成的目录。

  • 自定义生成目录终止的层数。

打包

go build main.go
Copy after login

-help

采用flag包动态控制参数,参数如下。

d:>main.exe -h
Usage of main.exe:
  -path string
        目录
  -tier int
        终止层数
Copy after login

运行

语法

main.exe -path <要生成的目录> -tier <终止层级>
注意:-tier,终止层数,0表示无限层,>0表示指定层数,默认为0
Copy after login

示例

此处-tier指定的是0,表示无限制生成,如果指定是1,就表示生成一层。

Teach you step by step how to develop a simple directory generator using Go language

结果

будет находиться в каталоге , который будет сгенерирован, и будет дополнительный directory.txt .

Teach you step by step how to develop a simple directory generator using Go language##Открыть следующим образом


Понимание основного кодаTeach you step by step how to develop a simple directory generator using Go language

flag

#fileObj

Teach you step by step how to develop a simple directory generator using Go language


Определите, является ли это каталогом, рекурсивно

Teach you step by step how to develop a simple directory generator using Go language


Сводка Teach you step by step how to develop a simple directory generator using Go language

На этот раз это больше похоже на скрипт для повседневного использования.Для решения практических задач лучше использовать для скрипта Python.

Но у Go есть большее преимущество: его можно скомпилировать в exe.

The above is the detailed content of Teach you step by step how to develop a simple directory generator using Go language. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:Go语言进阶学习
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!