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
+8.5k Golang : Copy map(hash table) example
+13.3k Golang : How to filter a map's elements for faster lookup
+14.2k Golang : How to add color to string?
+5.2k Javascript : Generate random key with specific length
+24.8k Golang : Convert(cast) string to uint8 type and back to string
+13.4k Golang : Get URI segments by number and assign as variable example
+17.1k Golang : How to get hour, minute, second from time?
+5.6k Elasticsearch : Shutdown a local node
+6.6k Golang : Generate human readable password
+21.4k Golang : Test file read write permission example
+12.9k Golang : Convert IP version 6 address to integer or decimal number
+23.4k Golang : Change file read or write permission example