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
+4k Fix Google Analytics Redundant Hostnames problem
+16k Golang : Check if IP address is version 4 or 6
+20k Golang : Encrypt and decrypt data with TripleDES
+7k Golang : Gomobile init produce "iphoneos" cannot be located error
+7.2k Golang : How To Use Panic and Recover
+8k Golang : Generate EAN barcode
+5.9k Golang : How to fix html/template : "somefile" is undefined error?
+16.2k Golang : delete and modify XML file content
+50.5k Golang : How to get struct field and value by name
+5.6k Golang : Embedded or data bundling example
+14.2k Golang : Validate hostname
+12.5k Golang : Query string with space symbol %20 in between