Copying a file in Go

mihalis's picture

This blog post will show some of the ways that you can copy a file in Go.

Using io.Copy()
The simplest way to copy a file is by using the io.Copy() function. You can find the entire Go code at
The most important part of the utility is the next Go code:

nBytes, err := io.Copy(destination, source)

So, with just a single call, you can copy a file. Although this is fast, it does not give you any flexibility or any control over the whole process.

Using ioutil.WriteFile() and ioutil.ReadFile()
You can copy a file in Go by using ioutil.WriteFile() and ioutil.ReadFile(). You can find the entire source file at
The most important part of readWriteAll.go is the next two Go statements:

input, err := ioutil.ReadFile(sourceFile)
err = ioutil.WriteFile(destinationFile, input, 0644)

The first statement reads the entire source file whereas the second statement writes the contents of the input variable to a new file.
Notice that reading the entire file and storing its contents to a single variable might not be very efficient when you want to copy huge files. Nevertheless, it works!

Using os.Read() and os.Write()
The last technique uses os.Read() for reading small portions of the input file into a buffer and os.Write() for writing the contents of that buffer to the new file. Notice that the size of the buffer is given as a command line argument, which makes the process very flexible.
You can find the entire code at
The most important statements of the implementation of the Copy() function are the next:

buf := make([]byte, BUFFERSIZE)
n, err := source.Read(buf)
_, err := destination.Write(buf[:n])

The first statement creates a byte slice with the desired size. The second statement reads from the input file whereas the third statement writes the contents of the buf buffer to the destination file.

Want to learn more about File I/O in Go?
Get my book Go Systems Programming from Packt or from

Want to be able to benchmark File I/O operations?
Get my book Mastering Go from Packt or from