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
+16.9k Golang : Get future or past hours, minutes or seconds
+12k Elastic Search : Return all records (higher than default 10)
+7.8k Golang : Auto-generate reply email with text/template package
+6.7k Golang : Squaring elements in array
+20.7k Curl usage examples with Golang
+6.1k Grep : How to grep for strings inside binary data
+24.4k Golang : Create PDF file from HTML file
+14k Golang : How to get URL port?
+25.6k Golang : Get executable name behind process ID example
+5.3k Swift : Get substring with rangeOfString() function example
+16.8k Golang : Check if IP address is version 4 or 6
+28.5k Golang : Saving(serializing) and reading file with GOB