Home
Last updated
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.
To copy a file is therefore a case of glueing together a few functions from the os
package. The process is
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)
}
}
The code example can be explained as follows.
Open
function from the os
module is used to read a file from disk.OpenFile
function is used to open a file. The first argument is the name of the file to be opened or created if it does not exist. The second argument represents the flags to be used on the file. In this case it is read and write and should be created if it does not exist. Finally the permissions on the file are set.Copy
function is then used from the io
package. This copies from the source file and writes it to the destination.Have an update or suggestion for this article? You can edit it here and send me a pull request.