Logo

Programming-Idioms

# 228 Copy a file
New implementation

Be concise.

Be useful.

All contributions dictatorially edited by webmasters to match personal tastes.

Please do not paste any copyright violating resource.

Please try to avoid dependencies to third-party libraries and frameworks.

Other implementations
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);
use File::Copy 'cp';
cp($src, $dst) or die $!;
import shutil
shutil.copy(src, dst)
require 'fileutils'
FileUtils.copy(src, dst)
use std::fs;
fs::copy(src, dst).unwrap();