How to copy a file in go

Oct 12, 2018 21:21 · 102 words · 1 minute read

Here is a snippet, which copies a file from source to destination.

package main

import (
	"io"
	"log"
	"os"
)

func main() {

	// Open original file
	source, err := os.Open("foo.txt")
	if err != nil {
		log.Fatal(err)
	}
	defer source.Close()

	// Create new file
	destination, err := os.Create("bar.txt")
	if err != nil {
		log.Fatal(err)
	}
	defer destination.Close()

	// Copy the bytes to destination from source
	bytesWritten, err := io.Copy(destination, source)
	if err != nil {
		log.Fatal(err)
	}
	log.Printf("Copied %d bytes.", bytesWritten)

	// Commit the file contents
	// Flushes memory to disk
	err = destination.Sync()
	if err != nil {
		log.Fatal(err)
	}
}