package main
import (
"io"
"fmt"
"os"
)
// copy file using os package
func copyFileUsingOsPackage(src, dst string) error {
bytesRead, err := os.ReadFile(src)
if err != nil {
return err
}
return os.WriteFile(dst, bytesRead, 0644)
}
// copy file using io package
func copyFileUsingIoPackage(src, dst string) (int64, error) {
source, err := os.Open(src)
if err != nil {
return 0, err
}
defer source.Close()
destination, err := os.Create(dst)
if err != nil {
return 0, err
}
defer destination.Close()
nBytes, err := io.Copy(destination, source)
return nBytes, err
}
func main() {
src := "/tmp/file-src.txt"
dst := "/tmp/file-dst.txt"
n, err := copyFileUsingIoPackage(src, dst)
if err != nil {
panic(err)
}
fmt.Printf("Copied %d bytes", n)
fmt.Println()
err = copyFileUsingOsPackage(src, dst)
if err != nil {
panic(err)
}
}
This example shows how to copy a file in Golang.