Programming-Idioms

This language bar is your friend. Select your favorite languages!

Idiom #228 Copy a file

Copy the file at path src to dst.

System.IO
File.Copy(src, dst, true); 
import "io/ioutil"
import "os"
func copy(dst, src string) error {
	data, err := ioutil.ReadFile(src)
	if err != nil {
		return err
	}
	stat, err := os.Stat(src)
	if err != nil {
		return err
	}
	return ioutil.WriteFile(dst, data, stat.Mode())
}
import "io"
import "os"
func copy(dst, src string) error {
	f, err := os.Open(src)
	if err != nil {
		return err
	}
	defer f.Close()
	stat, err := f.Stat()
	if err != nil {
		return err
	}
	g, err := os.OpenFile(dst, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, stat.Mode())
	if err != nil {
		return err
	}
	defer g.Close()
	_, err = io.Copy(g, f)
	if err != nil {
		return err
	}
	return os.Chmod(dst, stat.Mode())
}
import "io/ioutil"
import "os"
func copy(dst, src string) error {
	data, err := ioutil.ReadFile(src)
	if err != nil {
		return err
	}
	stat, err := os.Stat(src)
	if err != nil {
		return err
	}
	err = ioutil.WriteFile(dst, data, stat.Mode())
	if err != nil {
		return err
	}
	return os.Chmod(dst, stat.Mode())
}
new File(dst).bytes = new File(src).bytes
new File(src).withInputStream { input ->
    new File(dst).withOutputStream {output ->
        output << input
    }
}

const { copyFileSync } = require('fs');
copyFileSync(src, dst);
FileUtil
Success := CopyFile(src, dst);
import shutil
shutil.copy(src, dst)
require 'fileutils'
FileUtils.copy(src, dst)

Do you know the best way to do this in your language ?
New implementation...

Idiom created by

programming-idioms.org

Related idioms