ZetCode

Go copy file

last modified July 10, 2021

Go copy file tutorial shows how to copy a file in Golang. We show three ways to copy a file in Go.

We use the ioutil.ReadFile, ioutil.WriteFile, io.Copy, File.Read, File.Write functions to copy files.

Go copy file example

In the first example, we use the functions from the ioutil package.

copy_file.go
package main

import (
    "io/ioutil"
    "log"
)

func main() {

    src := "words.txt"
    dest := "words2.txt"

    bytesRead, err := ioutil.ReadFile(src)

    if err != nil {
        log.Fatal(err)
    }

    err = ioutil.WriteFile(dest, bytesRead, 0644)

    if err != nil {
        log.Fatal(err)
    }
}

The ioutil.ReadFile reads the specified file and returns the contents in a slice of bytes. The ioutil.WriteFile writes the specified slice of bytes into the destination file.

Go copy file example II

In the second example, we use the io.Copy function to copy a file.

copy_file2.go
package main

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

func main() {

    src := "words.txt"
    dst := "words2.txt"

    fin, err := os.Open(src)
    if err != nil {
        log.Fatal(err)
    }
    defer fin.Close()

    fout, err := os.Create(dst)
    if err != nil {
        log.Fatal(err)
    }
    defer fout.Close()

    _, err = io.Copy(fout, fin)

    if err != nil {
        log.Fatal(err)
    }
}

We open the source file with os.Open and create the destination file with os.Create; the handles to these two files are passed to the io.Copy function.

Go copy file example III

The File.Read reads up to len(b) bytes from the file, where b is a slice of bytes. The File.Write function writes the provided slice of bytes to the destination file.

copy_file3.go
package main

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

func main() {

    src := "words.txt"
    dst := "words2.txt"

    buf := make([]byte, 1024)

    fin, err := os.Open(src)
    if err != nil {
        log.Fatal(err)
    }

    defer fin.Close()

    fout, err := os.Create(dst)
    if err != nil {
        log.Fatal(err)
    }

    defer fout.Close()

    for {

        n, err := fin.Read(buf)
        if err != nil && err != io.EOF {
            log.Fatal(err)
        }

        if n == 0 {
            break
        }

        if _, err := fout.Write(buf[:n]); err != nil {
            log.Fatal(err)
        }
    }
}

We create a buffer of 1024 bytes. In a for loop, we read the bytes from the source file into the buffer and write the buffer into the destination file. When there is no more data to read, the File.Read function returns 0 and we break the loop.

In this tutorial, we have copied files in Golang.

List all Go tutorials.