Last updated

Copy a file in Go

How to copy a file in Go. The ioutil package does not offer a shorthand way of copying a file. Instead the os package should be used.

Estimated reading time: 2 minutes

Table of contents

No shorthand method

The ioutil package offers some of the common operations needed when working with files but nothing for copying files. Go tries to keep things lightweight so as operations become more complex the os package should be used. The os package operates at a slightly lower level and as such expects that files are explicitly closed after opening them. Reading the source code of the os package shows that many of the functions in the ioutil package are wrappers around the os package and remove the requirements to explicitly close files.

Copying a file

To copy a file is therefore a case of glueing together a few functions from the os package. The process is

Code example

The following shows an example of copying a file in Go.

package main

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

func main() {
  from, err := os.Open("./sourcefile.txt")
  if err != nil {
    log.Fatal(err)
  }
  defer from.Close()

  to, err := os.OpenFile("./sourcefile.copy.txt", os.O_RDWR|os.O_CREATE, 0666)
  if err != nil {
    log.Fatal(err)
  }
  defer to.Close()

  _, err = io.Copy(to, from)
  if err != nil {
    log.Fatal(err)
  }
}

Code example explaination

The code example can be explained as follows.

Further reading

Have an update or suggestion for this article? You can edit it here and send me a pull request.

Tags

Recent Posts