go 读取目录与cp

 

利用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

posted @   redrobot  阅读(39)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· SQL Server 2025 AI相关能力初探
· 单线程的Redis速度为什么快?
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
点击右上角即可分享
微信分享提示