How to copy a file in Go?

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/#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) } } 

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.

+6
source share
2 answers
 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. Check the number of bytes copied with the return value from io.Copy .

+5
source

The easiest way to make a copy of golang is http://golang.org/pkg/io/#Copy

0
source

Source: https://habr.com/ru/post/987678/


All Articles