Copying a file in Go

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

Using io.Copy() Link to heading

The simplest way to copy a file is by using the io.Copy() function. You can find the entire Go code at https://github.com/mactsouk/fileCopyGo/blob/master/ioCopy.go.

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() Link to heading

You can copy a file in Go by using ioutil.WriteFile() and ioutil.ReadFile(). You can find the entire source file at https://github.com/mactsouk/fileCopyGo/blob/master/readWriteAll.go.

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() Link to heading

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 https://github.com/mactsouk/fileCopyGo/blob/master/cpBuffer.go.

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? Link to heading

Get my book Go Systems Programming from Packt or from Amazon.com.

Want to be able to benchmark File I/O operations? Link to heading

Get my book Mastering Go, 2nd edition from Packt, Amazon.com, Amazon.co.uk or any other bookstore.

Or get Go Systems Programming also published by Packt Publishing.