package file import ( "fmt" "io" "os" "linkfog.com/public/lib/common" ) func CopyFile(dstFile, srcFile string, perm os.FileMode) error { srcStat, err := os.Stat(srcFile) if err != nil { return err } if !srcStat.Mode().IsRegular() { return fmt.Errorf("src file is not a regular file") } srcf, err := os.Open(srcFile) if err != nil { return err } defer srcf.Close() defer FadviseSwitch(srcf) dstf, err := os.OpenFile(dstFile, os.O_RDWR|os.O_CREATE|os.O_TRUNC, perm) if err != nil { return err } defer dstf.Close() defer FadviseSwitch(dstf) _, err = io.Copy(dstf, srcf) return err } func CopyFileWithCmd(dstFile, srcFile string) error { srcStat, err := os.Stat(srcFile) if err != nil { return err } if !srcStat.Mode().IsRegular() { return fmt.Errorf("src file is not a regular file") } out, err := common.ExecCmd(fmt.Sprintf("cp -f %s %s", srcFile, dstFile)) if err != nil { return fmt.Errorf("exec cp err: %s %s", err, out) } return nil } // CopyFileRateLimit 限速拷贝文件 func CopyFileRateLimit(dstFile, srcFile string) error { src, err := os.Open(srcFile) if err != nil { return err } defer src.Close() defer FadviseSwitch(src) dst, err := os.Create(dstFile) if err != nil { return err } defer dst.Close() defer FadviseSwitch(dst) _, err = CopyRateLimit(dst, src) if err != nil { return err } return nil }