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.3k Golang : Text file editor (accept input from screen and save to file)
+7k Golang : Ways to recover memory during run time.
+6.8k Golang : Convert(cast) io.Reader type to string
+17.6k Golang : Example for RSA package functions
+12.3k Swift : Convert (cast) Int to String ?
+12.5k Golang : Image to ASCII art example
+5.6k Golang : How to solve "too many .rsrc sections" error?
+17.3k Golang : Get download file size
+9k Golang : Sort and reverse sort a slice of integers
+11k Golang : Decompress zlib file example
+9.2k Golang : Channels and buffered channels examples
+5.9k Golang : Warp text string by number of characters or runes example