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
+8.8k Golang : What is the default port number for connecting to MySQL/MariaDB database ?
+10.3k Golang : Generate 403 Forbidden to protect a page or prevent indexing by search engine
+8.4k Linux/Unix : fatal: the Postfix mail system is already running
+15.6k Golang : Get digits from integer before and after given position example
+10.4k Golang : Get local time and equivalent time in different time zone
+11.2k Use systeminfo to find out installed Windows Hotfix(s) or updates
+14.1k Golang : Simple word wrap or line breaking example
+16.1k Golang : Loop each day of the current month example
+23k Golang : Print out struct values in string format
+16.4k Golang : Generate QR codes for Google Authenticator App and fix "Cannot interpret QR code" error
+5.5k Golang : Detect words using using consecutive letters in a given string
+28.4k Get file path of temporary file in Go