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
+10k Golang : Create S3 bucket with official aws-sdk-go package
+24.6k Mac/Linux and Golang : Fix bind: address already in use error
+4.7k Golang : Markov chains to predict probability of next state example
+17.3k Golang : Padding data for encryption and un-padding data for decryption
+9.1k Golang : How to tokenize source code with text/scanner package?
+3.5k Javascript : Detect when console is activated and do something about it
+10.8k Golang : Save webcamera frames to video file
+8.7k Golang : Bcrypting password
+8.9k Golang : Find and replace data in all files recursively
+10.1k CodeIgniter : How to check if a session exist in PHP?
+4.6k Golang : What is StructTag and how to get StructTag's value?
+4.2k Golang : Get FX sentiment from website example