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
+14.1k Elastic Search : Mapping date format and sort by date
+13k Golang : List objects in AWS S3 bucket
+23.1k Golang : Print out struct values in string format
+7.8k Swift : Convert (cast) String to Double
+16.9k Golang : Get input from keyboard
+13.1k Golang : Skip blank/empty lines in CSV file and trim whitespaces example
+27.4k Golang : Convert integer to binary, octal, hexadecimal and back to integer
+7.1k CloudFlare : Another way to get visitor's real IP address
+8.3k Golang: Prevent over writing file with md5 hash
+41.1k Golang : How to count duplicate items in slice/array?
+32.3k Golang : Copy directory - including sub-directories and files
+36.4k Golang : Validate IP address