Hands-On System Programming with Go
上QQ阅读APP看书,第一时间看更新

Copy

There's no unique function that makes it possible to copy a file, but this can easily be done with a reader and a writer with the io.Copy function. The following example shows how to use it to copy from one file to another:

func CopyFile(from, to string) (int64, error) {
src, err := os.Open(from)
if err != nil {
return 0, err
}
defer src.Close()
dst, err := os.OpenFile(to, os.O_WRONLY|os.O_CREATE, 0644)
if err != nil {
return 0, err
}
defer dst.Close()
return io.Copy(dst, src)
}