由于需要处理由目标操作系统及其configuration施加的一系列边缘情况和系统限制,所以健壮高效的副本在概念上是简单的,但并不容易实现。

os.Link(srcName, dstName)
Link()
Copy()
os.SameFile

优化的方法是在执行例程中复制字节,这样调用者就不会在字节拷贝上进行阻塞。 这样做会增加调用者处理成功/错误情况的复杂性。

CopyFile(src, dst string) (error)CopyFileAsync(src, dst string) (chan c, error)
 package main import ( "fmt" "io" "os" ) // CopyFile copies a file from src to dst. If src and dst files exist, and are // the same, then return success. Otherise, attempt to create a hard link // between the two files. If that fail, copy the file contents from src to dst. func CopyFile(src, dst string) (err error) { sfi, err := os.Stat(src) if err != nil { return } if !sfi.Mode().IsRegular() { // cannot copy non-regular files (eg, directories, // symlinks, devices, etc.) return fmt.Errorf("CopyFile: non-regular source file %s (%q)", sfi.Name(), sfi.Mode().String()) } dfi, err := os.Stat(dst) if err != nil { if !os.IsNotExist(err) { return } } else { if !(dfi.Mode().IsRegular()) { return fmt.Errorf("CopyFile: non-regular destination file %s (%q)", dfi.Name(), dfi.Mode().String()) } if os.SameFile(sfi, dfi) { return } } if err = os.Link(src, dst); err == nil { return } err = copyFileContents(src, dst) return } // copyFileContents copies the contents of the file named src to the file named // by dst. The file will be created if it does not already exist. If the // destination file exists, all it's contents will be replaced by the contents // of the source file. func copyFileContents(src, dst string) (err error) { in, err := os.Open(src) if err != nil { return } defer in.Close() out, err := os.Create(dst) if err != nil { return } defer func() { cerr := out.Close() if err == nil { err = cerr } }() if _, err = io.Copy(out, in); err != nil { return } err = out.Sync() return } func main() { fmt.Printf("Copying %s to %s\n", os.Args[1], os.Args[2]) err := CopyFile(os.Args[1], os.Args[2]) if err != nil { fmt.Printf("CopyFile failed %q\n", err) } else { fmt.Printf("CopyFile succeeded\n") } }