Quick actions

cmd+k|ctrl+k

Navigation

Languages

Working with files and I/O / File operations / Essential Go

Snippet info

Language

Go

Visibility

public

Author

kkowalczyk

Created

2019-03-26T10:15:34Z

Updated

2019-03-26T10:15:34Z

package main

import (
	"io"
	"log"
	"os"
)

// CopyFile copies a src file to dst
func CopyFile(dst, src string) error {
	srcFile, err := os.Open(src)
	if err != nil {
		return err
	}
	defer srcFile.Close()

	dstFile, err := os.Create(dst)
	if err != nil {
		return err
	}
	_, err = io.Copy(dstFile, srcFile)
	err2 := dstFile.Close()
	if err == nil && err2 != nil {
		err = err2
	}
	if err != nil {
		// delete the destination if copy failed
		os.Remove(dst)
	}
	return err
}

func main() {
	src := "main.go"
	dst := "main_copy.go"
	err := CopyFile(dst, src)
	if err != nil {
		log.Fatalf("CopyFile failed with '%s'\n", err)
	}
	os.Remove(dst)
}
INFO