Logo

Programming-Idioms

# 228 Copy a file
Copy the file at path src to dst.
Implementation
Go

Implementation edit is for fixing errors and enhancing with metadata. Please do not replace the code below with a different implementation.

Instead of changing the code of the snippet, consider creating another Go implementation.

Be concise.

Be useful.

All contributions dictatorially edited by webmasters to match personal tastes.

Please do not paste any copyright violating material.

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

Other implementations
import "os"
func copy(dst, src string) error {
	data, err := os.ReadFile(src)
	if err != nil {
		return err
	}
	stat, err := os.Stat(src)
	if err != nil {
		return err
	}
	err = os.WriteFile(dst, data, stat.Mode())
	if err != nil {
		return err
	}
	return os.Chmod(dst, stat.Mode())
}
uses FileUtil;
Success := CopyFile(src, dst);
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 shutil
shutil.copy(src, dst)
require 'fileutils'
FileUtils.copy(src, dst)
const { copyFileSync } = require('fs');
copyFileSync(src, dst);
System.IO
File.Copy(src, dst, true); 
new File(dst).bytes = new File(src).bytes
new File(src).withInputStream { input ->
    new File(dst).withOutputStream {output ->
        output << input
    }
}

use std::fs;
fs::copy(src, dst).unwrap();
use File::Copy 'cp';
cp($src, $dst) or die $!;
character, dimension(n_buff) :: buffer
open (newunit=u_r,file="src", action="read", form="unformatted", &
       access="stream")
open(newunit=u_w,file="dst", action="write", form="unformatted",&
     access="stream") 
inquire(unit=u_r,size=sz)
do while (sz > 0)
   n_chunk = min(sz, n_buff)
   read (unit=u_r) buffer(1:n_chunk)
   write (unit=u_w) buffer(1:n_chunk)
   sz = sz - n_chunk
end do
import 'dart:io';
File(src).copySync(dst);
with Ada.Directories;
Ada.Directories.Copy_File (Source_Name => Src,
                           Target_Name => Dst);
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
Files.copy(Path.of(src), Path.of(dst));