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
+13.6k Golang : How to check if a file is hidden?
+12.4k Golang : Transform comma separated string to slice example
+18.7k Golang : When to use public and private identifier(variable) and how to make the identifier public or private?
+20.3k Golang : Read directory content with os.Open
+6.9k Golang : Transform lisp or spinal case to Pascal case example
+12.2k Golang : Forwarding a local port to a remote server example
+5.1k Golang : Get FX sentiment from website example
+5.7k Facebook : How to force facebook to scrape latest URL link data?
+9.9k Golang : Text file editor (accept input from screen and save to file)
+3.4k Golang : Switch Redis database redis.NewClient
+12.4k Golang : Remove or trim extra comma from CSV
+4.4k Mac OSX : Get disk partitions' size, type and name