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
+10.5k Golang : Detect user location with HTML5 geo-location
+5.7k Fix sudo yum hang problem with no output or error messages
+13.2k Golang : Submit web forms without browser by http.PostForm example
+23k Golang : Time slice or date sort and reverse sort example
+5.5k Golang : Calculate diameter, circumference, area, sphere surface and volume
+5.8k Mac OSX : Find large files by size
+18.7k Golang : Read directory content with os.Open
+9k Android Studio : Checkbox for user to select options example
+11.2k Golang : Covert map/slice/array to JSON or XML format
+15.5k Golang : Get input from keyboard
+12k Golang : error parsing regexp: invalid or unsupported Perl syntax