I have the following function to copy a file (io.Reader actually) to the destination string location. However, it seems only part of the file is actually copied resulting in a corrupt 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'm using 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/#FileInfo
statinfo, err := reader.Stat()
if err != nil {
fmt.Println(err)
return nil
}
fmt.Println()
fmt.Println(statinfo.Size())
// Directory exists and is writable
err = CopyFile(reader, "/tmp/foo/"+f.Name())
if err != nil {
fmt.Println(err)
}
} else {
fmt.Println("Impossible to open the file:", err)
}
}
The current closest question I could has an accepted answer that recommends using hard/soft links and doesn't abort if the file already exists.
package main
import (
"fmt"
"io"
"os"
)
func main() {
srcFile, err := os.Open("test.txt")
check(err)
defer srcFile.Close()
destFile, err := os.Create("test_copy.txt") // creates if file doesn't exist
check(err)
defer destFile.Close()
_, err = io.Copy(destFile, srcFile) // check first var for number of bytes copied
check(err)
err = destFile.Sync()
check(err)
}
func check(err error) {
if err != nil {
fmt.Println("Error : %s", err.Error())
os.Exit(1)
}
}
This code works for me. Do check the number of bytes copied with the return value from io.Copy
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With