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.6k Golang : Calculate pivot points for a cross
+9.7k Golang : Ordinal and Ordinalize a given number to the English ordinal numeral
+8k Prevent Write failed: Broken pipe problem during ssh session with screen command
+9.4k Javascript : Read/parse JSON data from HTTP response
+15k Golang : Get timezone offset from date or timestamp
+6.1k Golang : Test input string for unicode example
+5.6k Golang : Fix opencv.LoadHaarClassifierCascade The node does not represent a user object error
+8.2k Golang : How to check variable or object type during runtime?
+24.9k Golang : Generate MD5 checksum of a file
+38.8k Golang : How to iterate over a []string(array)
+7.5k Golang : How to execute code at certain day, hour and minute?
+15.4k Golang : Convert date format and separator yyyy-mm-dd to dd-mm-yyyy