您的位置:首页 > 编程语言 > Go语言

Go语言通过指令的方式拷贝文件

2016-09-20 22:29 399 查看
package main

import (
"bufio"
"flag"
"fmt"
"io"
"os"
"strings"
)

func fileExists(fileName string) bool {
_, err := os.Stat(fileName)
return err == nil || os.IsExist(err)
}
func copyFile(src, dst string) (w int64, err error) {
srcFile, err := os.Open(src)
if err != nil {
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 copyFileAction(src, dst string, showProgress, force bool) {

if !force {
if fileExists(dst) {
fmt.Printf("%s exists override? y/n\n", dst)
reader := bufio.NewReader(os.Stdin)
data, _, _ := reader.ReadLine()
if strings.TrimSpace(string(data)) != "y" {
return
}
}
}
copyFile(src, dst)
}

func main() {
var showProgress, force bool
flag.BoolVar(&force, "f", false, "force copy when existing")
flag.BoolVar(&showProgress, "v", false, "explain what is being done")
flag.Parse()

if flag.NArg() < 2 {
flag.Usage()
return
}
copyFileAction(flag.Arg(0), flag.Arg(1), showProgress, force)
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  go语言