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
+4.7k Javascript : How to refresh page with JQuery ?
+42.4k Golang : Use wildcard patterns with filepath.Glob() example
+5k AWS S3 : Prevent Hotlinking policy
+15.3k Golang : Set up source IP address before making HTTP request
+8.5k Golang : interface - when and where to use examples
+9.3k Golang : ISO8601 Duration Parser example
+6.7k Javascript : How to check a browser's Do Not Track status?
+37.7k Golang : Remove dashes(or any character) from string
+7k Golang : Reverse text lines or flip line order example
+6k Javascript : How to get JSON data from another website with JQuery or Ajax ?
+7.8k Golang : Intercept and compare HTTP response code example
+25.1k Golang : Find files by extension