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
+37.7k Upload multiple files with Go
+8.9k Golang : Get final balance from bit coin address example
+9.2k Golang : Capture text return from exec function example
+10k Golang : Translate language with language package example
+15.7k Golang : How to convert(cast) IP address to string?
+9.4k Golang : How to check if a string with spaces in between is numeric?
+12.5k Golang : Encrypt and decrypt data with x509 crypto
+18.9k Golang : convert int to string
+5.4k Swift : Convert string array to array example
+20.3k Golang : Count number of digits from given integer value
+4.4k Javascript : How to show different content with noscript?
+22.8k Golang : Strings to lowercase and uppercase example