Golang : Copy file
Here’s an example to copy a file named “input.txt” to another file named “output.txt”.
Copying files can be done in several ways in Go. The example below is the easiest :
package main
import (
"io"
"fmt"
"os"
)
func main () {
// open files r and w
r, err := os.Open("input.txt")
if err != nil {
panic(err)
}
defer r.Close()
w, err := os.Create("output.txt")
if err != nil {
panic(err)
}
defer w.Close()
// do the actual work
n, err := io.Copy(w, r)
if err != nil {
panic(err)
}
fmt.Printf("Copied %v bytes\n", n)
}
With the file input.txt
in the same directory,
execute >go run copyfile.go
and output will something similar to this
Copied 561 bytes
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+6.9k Golang : Muxing with Martini example
+43.3k Golang : Convert []byte to image
+30.9k error: trying to remove "yum", which is protected
+20.2k Golang : How to get struct tag and use field name to retrieve data?
+46.6k Golang : Marshal and unmarshal json.RawMessage struct example
+7.4k Golang : Example of custom handler for Gorilla's Path usage.
+12.3k Golang : Simple client-server HMAC authentication without SSL example
+36.5k Golang : Save image to PNG, JPEG or GIF format.
+7k Golang : How to call function inside template with template.FuncMap
+13.7k Golang : Tutorial on loading GOB and PEM files
+9.7k Golang : Find correlation coefficient example
+14.6k Golang : How to check if your program is running in a terminal