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

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)
}

猜你喜欢

转载自blog.csdn.net/u012150370/article/details/52601348