Skip to content

Instantly share code, notes, and snippets.

@elazarl
Last active June 27, 2020 14:42
Show Gist options
  • Star 31 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save elazarl/5507969 to your computer and use it in GitHub Desktop.
Save elazarl/5507969 to your computer and use it in GitHub Desktop.
Unfortunately, searching for "golang copy file" gives subtly wrong code snippets (e.g. https://groups.google.com/d/msg/golang-nuts/JNyQxQLyf5o/kbGnTUK32TkJ that don't check close error code). This is an attempt to copy file content from `src` to `dst`
package cp
import (
"io"
"os"
)
func cp(dst, src string) error {
s, err := os.Open(src)
if err != nil {
return err
}
// no need to check errors on read only file, we already got everything
// we need from the filesystem, so nothing can go wrong now.
defer s.Close()
d, err := os.Create(dst)
if err != nil {
return err
}
if _, err := io.Copy(d, s); err != nil {
d.Close()
return err
}
return d.Close()
}
@RoySegall
Copy link

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment