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
+9.7k Golang : Channels and buffered channels examples
+23.6k Golang : Upload to S3 with official aws-sdk-go package
+30.1k Golang : How to redirect to new page with net/http?
+10.1k Android Studio : Simple input textbox and intercept key example
+14.9k Golang : Get timezone offset from date or timestamp
+10.8k Golang : Web routing/multiplex example
+5.9k Golang & Javascript : How to save cropped image to file on server
+15.8k Golang : How to check if input from os.Args is integer?
+16.2k Golang : How to implement two-factor authentication?
+7.5k Golang : Reverse a string with unicode
+28.8k Golang : Saving(serializing) and reading file with GOB
+7.5k Golang : Ways to recover memory during run time.