I have the following function to copy a file (actually io.Reader) to the destination of the target line. However, it appears that only part of the file is actually copied, resulting in a damaged file. What am I doing wrong?
func CopyFile(in io.Reader, dst string) (err error) { // Does file already exist? Skip if _, err := os.Stat(dst); err == nil { return nil } err = nil out, err := os.Create(dst) if err != nil { fmt.Println("Error creating file", err) return } defer func() { cerr := out.Close() if err == nil { err = cerr } }() var bytes int64 if bytes, err = io.Copy(out, in); err != nil { fmt.Println("io.Copy error") return } fmt.Println(bytes) err = out.Sync() return }
I use this with the filepath.Walk(dir, visit) method to process files in a directory.
// Process each matching file on our walk down the filesystem func visit(path string, f os.FileInfo, err error) error { if reader, err := os.Open(path); err == nil { defer reader.Close() // http://golang.org/pkg/os/
In the current upcoming question , I may have an accepted answer that recommends using hard / soft links and does not cancel if the file already exists.
source share