Go language traverses files in depth

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

      • General methods do not use Pathfilepath packages
      • Go's FilePath pack

The go language provides a lot of packages, and we can do a lot of interesting things based on these packages, and we'll look at how to use the Go language to traverse the file in this section.

General method (do not use Path/filepath package)

The more intuitive way to do this is to facilitate the file in a way that is recursive to a directory:

func  walkdir (dirpath string , Depth int ) { if  depth > Depth{//greater than set depth  return } files, err: = Ioutil. ReadDir (Dirpath) //read directory under file  if  Err! = nil  {return } for  _, File: = range  files{if  file. Isdir () {walkdir (Dirpath +  + file. Name (), Depth+1 ) continue }else  {...} }}
    • Use the ioutil method in the package to ReadDir read the DIR information in this directory first
    • filedetermines whether it is a directory based on the information returned
      • Recursive call method if it is a directory walkDir
      • Otherwise, the file is processed

This completes a traversal of the file, which is a simple traversal operation. Of course, due to recursive invocation, the memory consumption is compared.

Go's FilePath pack

FilePath package implements a practical approach to file paths compatible with each operating system

The main use of this time is two methods

Method definition
Walkfunc Type Walkfunc func (path string, info OS. FileInfo, err Error) Erro
Walk Func Walk (Root string, WALKFC Walkfunc) error

We can see that there is actually a call to the Walkfunc method inside the walk, which is used to filter.

Walk (Root stirng, WALKFN Walkfunc) Error method

walk方法会遍历root下的所有文件(包含root)并对每一个目录和文件都调用walkFunc方法。在访问文件和目录时发生的错误都会通过error参数传递给WalkFunc方法。文件是按照词法顺序进行遍历的,这个通常让输出更漂亮,但是也会导致处理非常大的目录时效率会降低。另外,walk函数不会遍历符号链接。

Walkfunc (path string, info OS. FileInfo, err Error) Error function

Walk函数在遍历文件时调用。调用时将参数传递给path,这是一个绝对路径,也就是Walk函数中的root作为前缀。将root + 文件名作为path传递给WalkFunc函数。例如在"Dir"目录下遍历到"a"文件,则path="Dir/a"Info是path所指向文件的文件信息。如果在遍历过程中出现了问题,传入参数err会描述这个问题。WalkFunc函数可以处理这个问题,Walk将不会再深入该目录。如果函数会返回一个错误,Walk函数会终止执行;只有一个例外,我们也通常用这个来跳过某些目录。当WalkFunc的返回值是filepaht.SkipDir时,Walk将会跳过这个目录,照常执行下一个文件。

Example:

Import "Path/filepath"funcWalkdir (dirstring) {files, err: = Ioutil. ReadDir (dir)ifErr! =Nil{        ...    } for_, File: = ranges files{FileName: = file. Name () filepath. Walk (filename,func(Pathstring, Fi os. FileInfo, err Error) error{depth: = strings. Count (Path,"/")-strings. Count (filename,"/")ifDepth > depth{returnFilePath. Skipdir}ifErr! =Nil{//Handling file read exceptions}ifFi. Isdir () {satisfies the condition without a tube does not satisfy the conditionreturnFilePath. Skipdir}})}}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.