Go language traversal files in the directory

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


Import (
"FMT"
"Io/ioutil"
"OS"
// "Path/filepath"
// "Strings"
)


VAR (
files []string
)


Get all files and directories under the specified directory
Func Listdir (dirpth string) (err error) {
Fmt. Println (dirpth)
Dir, err: = Ioutil. ReadDir (dirpth)
If err! = Nil {
return err
}
PTHSEP: = string (OS. PathSeparator)
// suffix = strings. ToUpper (suffix)//ignore suffix matching case

For _, Fi: = Range dir {

If Fi. Isdir () {//Ignore directory
Files1 = Append (Files1, Dirpth+pthsep+fi. Name ())
Listdir (dirpth + pthsep + fi. Name ())
Fmt. Println (dirpth + pthsep + fi. Name ())
}else{
Fmt. Println ("s")
Files d= append (files, Dirpth+pthsep+fi. Name ())
}
}
return Nil
}

Func Main () {
_ = Listdir ("/mnt/hgfs/share/mygo/src/yeesec/alchemist")

For _, Table1: = Range Files {
Fmt. Println (table1)
}

}

Or

Package Main
Import(
  "FMT"
  "Io/ioutil"
  "OS"
  //   "Path/filepath"
  //   "strings"
)
Get all files and directories under the specified directory
Funclistdir (dirpthstring)(Files[]string, Files1  []string,errerror){
  //fmt. Println (dirpth)
 dir,err: =ioutil. ReadDir (dirpth)
  iferr!=nil{
  returnnil,nil,err
    }
 pthsep: =string(OS. PathSeparator)
  //   suffix=strings. ToUpper (suffix)//Ignore suffix matching case
  for_,fi: =rangedir{
  iffi. Isdir (){//  Ignore directory
 files1=append(files1,dirpth+pthsep+fi. Name ())
 listdir (dirpth+pthsep+fi. Name ())
 }else{
  //fmt. Println ("s")
 files=append(Files,Dirpth+pthsep+fi. Name ())
        }
    }
  returnfiles,files1,Nil
}
FuncMain (){
 files,files1,_: =listdir ("/mnt/hgfs/share/mygo/src/yeesec/alchemist" )
  for_,table: =rangefiles1{
 temp,_,_:=listdir (table)
  for_,temp1: =rangetemp{
 files=append(Files,temp1)
        }
    }
  for_,table1: =rangefiles{
 FMT. Println (table1)
    }
}



Related Article

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.