How to Copy a File in Go
Created
Modified
Using io.Copy Function
You can copy a file using the io.Copy() function. For example,
package main
import (
"io"
"os"
)
// Copy the src file to dst.
func Copy(src, dst string) error {
in, err := os.Open(src)
if err != nil {
return err
}
defer in.Close()
out, err := os.Create(dst)
if err != nil {
return err
}
_, err = io.Copy(out, in)
if err != nil {
return err
}
return nil
}
func main() {
Copy("access.log", "access.1.log")
}
access.1.log
Using ioutil.WriteFile Function
The following example should cover whatever you are trying to do:
package main
import (
"io/ioutil"
)
// Copy the src file to dst.
func Copy(src, dst string) error {
data, err := ioutil.ReadFile(src)
if err != nil {
return err
}
err = ioutil.WriteFile(dst, data, 0644)
if err != nil {
return err
}
return nil
}
func main() {
Copy("access.log", "access.1.log")
}
access.1.log