...

/

Copying Files

Copying Files

This lesson provides an implementation of copying files in Go.

We'll cover the following...

How do you copy a file to another file? The simplest way is using Copy from the io package:

Press + to interact
main.go
source.txt
package main
import (
"fmt"
"io"
"os"
)
func main() {
CopyFile("output/target.txt", "source.txt")
fmt.Println("Copy done!")
}
func CopyFile(dstName, srcName string) (written int64, err error) {
src, err := os.Open(srcName)
if err != nil {
return
}
defer src.Close()
dst, err := os.OpenFile(dstName, os.O_WRONLY|os.O_CREATE, 0644)
if err != nil {
return
}
defer dst.Close()
return io.Copy(dst, src)
}

In the code above, we isolate the copying of the file in a function CopyFile, which takes as parameters first the destination file, and secondly the source file. (see line 9 ...