Home  >  Article  >  Backend Development  >  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

Go语言进阶学习
Go语言进阶学习forward
2023-07-25 16:55:53774browse

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)
}

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

实现的功能

  • 自定义要生成的目录。

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

打包

go build main.go

-help

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

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

运行

语法

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

示例

此处-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!

Statement:
This article is reproduced at:Go语言进阶学习. If there is any infringement, please contact admin@php.cn delete