利用ioutil的ReadDir方法:
package main
import (
"fmt"
"io/ioutil"
)
func main() {
files, _ := ioutil.ReadDir("./")
for _, f := range files {
fmt.Println(f.Name())
}
}
利用filepath的Glob方法:
package main
import (
"fmt"
"path/filepath"
)
func main() {
files, _ := filepath.Glob("*")
fmt.Println(files) // contains a list of all files in the current directory
}
利用walk:
package main
import (
"fmt"
"os"
"path/filepath"
)
func main() {
var files []string
root := "/some/folder/to/scan"
err := filepath.Walk(root, func(path string, info os.FileInfo, err error) error {
files = append(files, path)
return nil
})
if err != nil {
panic(err)
}
for _, file := range files {
fmt.Println(file)
}
}
walkfunc:
package main
import (
"fmt"
"log"
"os"
"path/filepath"
)
func visit(files *[]string) filepath.WalkFunc {
return func(path string, info os.FileInfo, err error) error {
if err != nil {
log.Fatal(err)
}
*files = append(*files, path)
return nil
}
}
func main() {
var files []string
root := "/some/folder/to/scan"
err := filepath.Walk(root, visit(&files))
if err != nil {
panic(err)
}
for _, file := range files {
fmt.Println(file)
}
}
cp 文件:
package main
import (
"bufio"
"flag"
"fmt"
"io"
"os"
"strings"
)
var (
showProcess bool
forceCp bool
)
func init() {
flag.BoolVar(&showProcess, "v", false, "show copy msg")
flag.BoolVar(&forceCp, "f", false, "false to cp")
flag.Parse()
}
func main() {
if flag.NArg() < 2 {
flag.Usage()
fmt.Println("error: Need dst and src file!!")
return
}
CopyFile(flag.Arg(0), flag.Arg(1))
}
func fileExist(filename string) bool {
_, err := os.Stat(filename)
return err == nil || os.IsExist(err)
}
func copyActioin(dst, src string) (w int64, err error) {
var (
srcFile *os.File
dstFile *os.File
)
srcFile, err = os.Open(src)
if err != nil {
fmt.Println(err.Error())
return
}
defer srcFile.Close()
dstFile, err = os.Create(dst)
if err != nil {
fmt.Println(err.Error())
return
}
defer dstFile.Close()
return io.Copy(dstFile, srcFile)
}
func CopyFile(dst, src string) {
if !forceCp {
if fileExist(dst) {
fmt.Printf("%s existed overwrite?[y/n]", dst)
reader := bufio.NewReader(os.Stdin)
data, _, _ := reader.ReadLine()
if strings.ToLower(strings.TrimSpace(string(data)))[0] != 'y' {
return
}
}
}
copyActioin(dst, src)
if showProcess {
fmt.Printf("%s =====>> %s", src, dst)
}
}
参考:
https://blog.csdn.net/xielingyun/article/details/56484004
https://loocode.com/post/shi-yong-go-lie-chu-wen-jian-jia-zhong-de-wen-jian
https://blog.csdn.net/weixin_30746129/article/details/83276117
标签:files,main,读取,err,fmt,func,go,cp,os From: https://www.cnblogs.com/rebrobot/p/17393796.html