go语言学习笔记----模拟实现文件拷贝函数

实例1

//main
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 {
                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 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)
        if showProgress {
                fmt.Printf("'%s'->'%s'\n", 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 }
//取第0个参数与第一个参数作为源文件名跟目标文件名 copyFileAction(flag.Arg(0), flag.Arg(1), showProgress, force) }

示例2:Golang实现文件拷贝功能

package main

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

// 编写一个函数,接收两个文件路径:
func copyFile(dstFileName string, srcFileName string) (written int64, err error) {
    srcFile, err := os.Open(srcFileName)
    if err != nil {
        fmt.Printf("open file error = %v\n", err)
    }
    defer srcFile.Close()

    //通过srcFile,获取到READER
    reader := bufio.NewReader(srcFile)

    //打开dstFileName
    dstFile, err := os.OpenFile(dstFileName, os.O_WRONLY|os.O_CREATE, 0666)
    if err != nil {
        fmt.Printf("open file error = %v\n", err)
        return
    }

    //通过dstFile,获取到WRITER
    writer := bufio.NewWriter(dstFile)
    //writer.Flush()

    defer dstFile.Close()

    return io.Copy(writer, reader)
}


func main() {
    //调用copyFile完成文件拷贝
    srcFile := "e:/copyFileTest02.pdf"
    dstFile := "e:/Go/tools/copyFileTest02.pdf"

    _, err := copyFile(dstFile, srcFile)
    if err == nil {
        fmt.Println("拷贝文件正常...")
    } else {
        fmt.Printf("拷贝文件出错了... err =%v\n", err)
    }
}

说明:

1, 使用了带缓存的 bufio.NewReader(srcFile) 和 bufio.NewWriter(dstFile),一边读一边写,这样支持拷贝较大的文件;

2,defer dstFile.Close() 切记使用defer 来关闭打开的文件,避免内存泄漏;