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
+5.7k Golang : Check if password length meet the requirement
+11.2k Golang : Search and extract certain XML data example
+11.4k Golang : Exit, terminating or aborting a program
+8.2k Golang : How to get garbage collection data?
+17.8k Golang : Fix cannot download, $GOPATH not set error
+4.1k Golang : Display packages names during compilation
+11.4k Golang : "https://" not allowed in import path
+6.5k Golang : What fmt.Println() can do and println() cannot do
+14.8k Golang : Delete files by extension
+16.4k Golang : Aligning strings to right, left and center with fill example
+20.4k Golang : Use TLS version 1.2 and enforce server security configuration over client