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.4k Golang : Web(Javascript) to server-side websocket example
+6.5k Golang : How to determine if request or crawl is from Google robots
+7.2k Golang : Check if one string(rune) is permutation of another string(rune)
+10.4k Swift : Convert (cast) String to Integer
+6.5k Golang : Warp text string by number of characters or runes example
+9.5k Golang : Validate IPv6 example
+4.9k Nginx and PageSpeed build from source CentOS example
+5.7k Linux : Disable and enable IPv4 forwarding
+17.2k Google Chrome : Your connection to website is encrypted with obsolete cryptography
+10.5k Golang : Allow Cross-Origin Resource Sharing request
+9.7k Golang : Detect number of active displays and the display's resolution
+5.2k Python : Convert(cast) string to bytes example