Taskintro
Copy a file
Also called duplicate a file, cp, copy a file with its permissions, file copy.
Copy the bytes and the permission bits of a file to a new path, replace a file at that path, and report an error when the two paths name the same file.
- Evidence
- Code in 10 languages
Task
Copy the file at path src to the path dst. After the call, dst has the same bytes as src, and the same permission bits. If a file is at dst, replace it. src does not change. Copy the bytes with no change: no text mode, no change of line ends, and a NUL byte is a byte.
Report an error, and change no file, when src is missing, when the directory of dst is missing, when src or dst is a directory, and when src and dst name the same file. The last case is important: a copy that opens dst for writing first makes the file empty, and then it has no data to read. See the pitfalls.
The permission bits are part of the task, because a copy of a script must stay executable. The times, the owner, the access control lists and other metadata are not part of the task. No copy function copies all of them. Python says: "Even the higher-level file copying functions ( shutil.copy() , shutil.copy2() ) cannot copy all file metadata. On POSIX platforms, this means that file owner and group are lost as well as ACLs."
SQL, regular expressions, HTML and CSS do not apply, because they do not copy files.
Solutions
Most languages have a copy function, and it is better than a loop that reads and writes, because it can use a fast call of the operating system. The Python documentation says that the copy functions "may use platform-specific “fast-copy” syscalls in order to copy the file more efficiently". On Linux, copy_file_range "performs an in-kernel copy between two file descriptors without the additional cost of transferring data from the kernel to user space and then back into the kernel." On a file system with reflinks, a copy can share the blocks of the file: "this ioctl(2) operation can be used to make some of the data in the src_fd file appear in the dest_fd file by sharing the underlying storage, which is faster than making a separate physical copy of the data." The new file gets its own blocks only when a program writes to it ("copy on write").
Each solution checks the directory and same-file cases first, because the copy functions do not agree on them.
- Python.
shutil.copy(src, dst). "copy() copies the file data and the file’s permission mode (see os.chmod() ). Other metadata, like the file’s creation and modification times, is not preserved." For the same file it raisesshutil.SameFileError. But "If dst specifies a directory, the file will be copied into dst using the base filename from src", so the code raisesIsADirectoryErrorfirst.shutil.copyfilecopies only the bytes: "Copy the contents (no metadata) of the file named src to a file named dst". - JavaScript and TypeScript (Node.js).
fsPromises.copyFile(src, dst). "By default, dest is overwritten if it already exists." The code comparesdevandinofromstatfor the same file, givesEISDIRfor a directory, and callschmodafter the copy.COPYFILE_FICLONEin the mode argument asks for a reflink: "If the platform does not support copy-on-write, then a fallback copy mechanism is used." - Java.
Files.copy(src, dst, StandardCopyOption.REPLACE_EXISTING), thenFiles.setPosixFilePermissions, because "File attributes are not required to be copied to the target file." The code throws aFileSystemExceptionfor the other cases, becauseFiles.copygives no error for them: "except if the source and target are the same file, in which case the method completes without copying the file", and "If the file is a directory then an empty directory is created in the target location". - C#.
File.Copy(src, dst, overwrite: true). "The attributes of the original file are retained in the copied file." On Unix, the code also callsFile.SetUnixFileModeafter the copy. For a directory atsrcordst, it throws anIOException. For the same file,File.Copythrows anIOException; the native tests check this for the same path and for a hard link. - Go. Go has no function that copies one file. (
os.CopyFScopies a tree, and it "will not overwrite existing files".) So the code openssrc, checksos.SameFile, opensdstwithO_TRUNC, and callsio.Copy. "If src implements WriterTo , the copy is implemented by calling src.WriteTo(dst). Otherwise, if dst implements ReaderFrom , the copy is implemented by calling dst.ReadFrom(src)." So on Linux, the copy uses the fast calls. The code returns the error ofCloseand callsChmod. - Rust.
std::fs::copy(src, dst). "This function will also copy the permission bits of the original file to the destination file." It is not safe for the same file: "Note that if from and to both point to the same file, then the file will likely get truncated by this operation." So the code compares the device and inode numbers first. - C. C has no copy function. The code opens
srcwithopen, checks the same file withfstatandstat, opensdstwithO_WRONLY | O_CREAT | O_TRUNC, and copies with a loop ofreadandwrite. Each call can do less than the full count, andEINTRcan stop it, so both are loops. Thenfchmod, and the result ofcloseis checked. - C++.
std::filesystem::copy_file(src, dst, copy_options::overwrite_existing, ec). For a new file, it "copies the contents and the attributes of the file". For the other cases it reports an error ("If !filesystem::is_regular_file(from) (either because the source file doesn't exist or because it is not a regular file), report an error"), but the error code is not the same in each library, so the code checks the cases first. The function is in a namespace, because a call withstd::filesystem::patharguments also findsstd::filesystem::copy_file. - Bash.
cp -p -- "$src" "$dst". With no-p,cpopens a file atdst"using dest_file as the path argument, and the bitwise-inclusive OR of O_WRONLY and O_TRUNC as the oflag argument", so the file keeps its old permission bits.-pcopies "The file permission bits and the S_ISUID and S_ISGID bits", and also the times.cpcopies into a directory atdst, so the function returns status 1 for a directory, and for the same file (-ef).
On Windows, the copy function is CopyFileEx. Rust says: "On Windows, this function currently corresponds to CopyFileEx", and "On MacOS, this function corresponds to fclonefileat and fcopyfile".
Edge cases
The cases are in cases/basic.jsonl and cases/edge.jsonl. Each test makes the files in a new temporary directory, calls the function, and checks the bytes at dst and at src.
copyandreplace-existing: a new path, and a path with a longer file. The copy must truncate the old file, or the end of the old text stays.empty-file: an empty file replaces a file with text.other-directory:a.txttosub/a.txt. The directory must exist.name-with-spacesandnon-ascii-name:copy of my notes.txtandcafé 日本.txt. A shell solution must quote the names.binary-data: the bytes00 0D 0A C3 BF 00. A copy in text mode can change0D 0Aon Windows, and a copy with C strings stops at the first00.- Errors, in
cases/errors.jsonl: a missingsrcand a missing directory ofdstgive not-found, a directory atsrcordstgives is-a-directory, and the same path gives same-file.
The native tests also check that dst gets the permission bits 0750 of src, also when it replaces a file with 0640; that a file of 5000003 bytes, more than one buffer, is copied byte for byte; that a symbolic link at src gives a copy of its target, not a link; and that a hard link to src at dst gives same-file, and the file keeps its data.
Pitfalls
- A copy of a file onto itself. A copy that opens
dstwith truncation makes the file empty before it reads it. The two paths can be different and still name one file, for example through a hard link or a symbolic link:
This code runs but gives a wrong answer on purpose.
import os
import tempfile
def naive_copy(src, dst):
with open(src, "rb") as f, open(dst, "wb") as out: # "wb" makes dst empty
out.write(f.read())
with tempfile.TemporaryDirectory() as dir:
path = os.path.join(dir, "report.txt")
with open(path, "w") as f:
f.write("alpha\n")
naive_copy(path, path) # src and dst are the same file
print("size:", os.path.getsize(path))
size: 0
Compare the device and inode numbers of the two files before the copy, as shutil.copy and cp do. A check of the two path strings is not sufficient.
- A copy that keeps the old permission bits.
cpwith no-pkeeps the mode of a file atdst, so a new version of a script is not executable:
This code runs but gives a wrong answer on purpose.
dir=$(mktemp -d)
printf '#!/bin/sh\necho new\n' >"$dir/new.sh"
printf '#!/bin/sh\necho old\n' >"$dir/run.sh"
chmod 755 "$dir/new.sh"
chmod 644 "$dir/run.sh" # the old copy is not executable
cp "$dir/new.sh" "$dir/run.sh"
ls -l "$dir/run.sh" | cut -c1-10
rm -r "$dir"
-rw-r--r--
shutil.copyfile, Java Files.copy and a loop of read and write can also give dst other bits than src. Set the bits after the copy.
- A copy that changes the time.
shutil.copygives the copy the time of the copy. Tools that compare times, such as build tools and backup programs, then take the copy for a new file.shutil.copy2also copies the times:
import os
import shutil
import tempfile
with tempfile.TemporaryDirectory() as dir:
src = os.path.join(dir, "data.csv")
with open(src, "w") as f:
f.write("a,b\n")
os.utime(src, (1_600_000_000, 1_600_000_000)) # an old file
shutil.copy(src, os.path.join(dir, "copy.csv"))
shutil.copy2(src, os.path.join(dir, "copy2.csv"))
for name in ("copy.csv", "copy2.csv"):
same = os.path.getmtime(os.path.join(dir, name)) == os.path.getmtime(src)
print(name, "has the time of src:", same)
copy.csv has the time of src: False
copy2.csv has the time of src: True
- A copy that a reader sees in parts. A copy is not atomic. Node says: "No guarantees are made about the atomicity of the copy operation." A program that opens
dstduring the copy reads a part of the file. Ifdstmust always be a full file, copy to a temporary name in the directory ofdst, and then rename it overdst, as in Rename a file:
import os
import shutil
import tempfile
def copy_whole(src, dst):
dir = os.path.dirname(os.path.abspath(dst))
fd, tmp = tempfile.mkstemp(dir=dir, prefix=".tmp-")
os.close(fd)
try:
shutil.copy(src, tmp)
os.replace(tmp, dst) # a reader sees the old dst or the full copy
except BaseException:
os.unlink(tmp)
raise
with tempfile.TemporaryDirectory() as dir:
src, dst = os.path.join(dir, "new.conf"), os.path.join(dir, "app.conf")
for path, text in ((src, "port = 9090\n"), (dst, "port = 8080\n")):
with open(path, "w") as f:
f.write(text)
copy_whole(src, dst)
with open(dst) as f:
print(f.read(), end="")
print(sorted(os.listdir(dir)))
port = 9090
['app.conf', 'new.conf']
-
A copy that reads the whole file into memory. Code such as
out.write(f.read())needs as much memory as the file. For a large file, use the copy function of the language, or a loop with a buffer of a fixed size, as the C solution does. -
A copy of a symbolic link. Most copy functions follow a link at
srcand copy the target. Node says: "If src is a symbolic link, the target file is copied." To copy the link itself, usefollow_symlinks=Falsein Python orLinkOption.NOFOLLOW_LINKSin Java.
Related tasks
- Rename a file
- Check whether a file exists
- Read and write with buffers
- Create a temporary file
- Get the size of a file
- File permissions
Code
The build runs the native tests of each language in a pinned toolchain.
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/copy-a-file/.
import errno
import os
import shutil
def copy_file(src: str | os.PathLike, dst: str | os.PathLike) -> None:
"""Copies the bytes and the permission bits of the file at src to dst.
shutil.copy uses the fast copy call of the platform, and it raises
shutil.SameFileError when src and dst are the same file. But it copies
into a directory at dst, so the function raises IsADirectoryError first.
Each other error, for example a missing src, comes out as an OSError.
"""
if os.path.isdir(dst):
raise IsADirectoryError(errno.EISDIR, os.strerror(errno.EISDIR), os.fspath(dst))
shutil.copy(src, dst)
test_copy_file.py 93 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/copy-a-file/.
import os
import shutil
import stat
from pathlib import Path
import pytest
from copy_file import copy_file
# name: (src, dst, content of src, content of dst or None)
CASES = {
"copy": ("a.txt", "b.txt", "alpha\n", None),
"replace-existing": ("a.txt", "b.txt", "alpha\n", "beta, a longer text\n"),
"empty-file": ("a.txt", "b.txt", "", "beta\n"),
"other-directory": ("a.txt", "sub/a.txt", "alpha\n", None),
"name-with-spaces": ("my notes.txt", "copy of my notes.txt", "alpha\n", None),
"non-ascii-name": ("a.txt", "café 日本.txt", "alpha\n", None),
"binary-data": ("a.bin", "b.bin", "\0\r\n\xff\0", None),
}
@pytest.mark.parametrize("name", CASES)
def test_cases(tmp_path: Path, name: str) -> None:
src_rel, dst_rel, src_content, dst_content = CASES[name]
src, dst = tmp_path / src_rel, tmp_path / dst_rel
dst.parent.mkdir(exist_ok=True)
if dst_content is not None:
dst.write_bytes(dst_content.encode())
src.write_bytes(src_content.encode())
copy_file(src, dst)
assert dst.read_bytes() == src_content.encode()
assert src.read_bytes() == src_content.encode()
def test_missing(tmp_path: Path) -> None:
with pytest.raises(FileNotFoundError):
copy_file(tmp_path / "a.txt", tmp_path / "b.txt")
(tmp_path / "a.txt").write_text("alpha\n")
with pytest.raises(FileNotFoundError):
copy_file(tmp_path / "a.txt", tmp_path / "no-such-dir" / "b.txt")
def test_directories(tmp_path: Path) -> None:
(tmp_path / "dir").mkdir()
(tmp_path / "a.txt").write_text("alpha\n")
with pytest.raises(IsADirectoryError):
copy_file(tmp_path / "dir", tmp_path / "b.txt")
with pytest.raises(IsADirectoryError):
copy_file(tmp_path / "a.txt", tmp_path / "dir")
assert os.listdir(tmp_path / "dir") == []
assert not (tmp_path / "b.txt").exists()
def test_same_file(tmp_path: Path) -> None:
src = tmp_path / "a.txt"
src.write_text("alpha\n")
os.link(src, tmp_path / "b.txt")
for dst in (src, tmp_path / "b.txt"):
with pytest.raises(shutil.SameFileError):
copy_file(src, dst)
assert src.read_text() == "alpha\n"
def test_mode(tmp_path: Path) -> None:
src, dst = tmp_path / "a.sh", tmp_path / "b.sh"
src.write_text("echo alpha\n")
os.chmod(src, 0o750)
copy_file(src, dst)
assert stat.S_IMODE(dst.stat().st_mode) == 0o750
other = tmp_path / "c.sh"
other.write_text("beta\n")
os.chmod(other, 0o640)
copy_file(src, other)
assert stat.S_IMODE(other.stat().st_mode) == 0o750
def test_large_file(tmp_path: Path) -> None:
data = bytes(i * 7 % 251 for i in range(5_000_003))
src, dst = tmp_path / "big.bin", tmp_path / "copy.bin"
src.write_bytes(data)
copy_file(src, dst)
assert dst.read_bytes() == data
def test_link_at_src(tmp_path: Path) -> None:
(tmp_path / "target.txt").write_text("alpha\n")
os.symlink("target.txt", tmp_path / "link.txt")
copy_file(tmp_path / "link.txt", tmp_path / "b.txt")
assert not (tmp_path / "b.txt").is_symlink()
assert (tmp_path / "b.txt").read_text() == "alpha\n"
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/copy-a-file/.
#include "copy_file.hpp"
namespace fs = std::filesystem;
void files::copy_file(const fs::path& src, const fs::path& dst, std::error_code& ec) {
// std::filesystem::copy_file reports an error for these cases too, but
// the error code is not the same in each library, so the code checks
// them first.
fs::file_status s = fs::status(src, ec);
if (ec) return;
if (fs::is_directory(s)) {
ec = std::make_error_code(std::errc::is_a_directory);
return;
}
fs::file_status d = fs::status(dst, ec);
ec.clear();
if (fs::is_directory(d)) {
ec = std::make_error_code(std::errc::is_a_directory);
return;
}
if (fs::exists(d) && fs::equivalent(src, dst, ec)) {
ec = std::make_error_code(std::errc::invalid_argument);
return;
}
if (ec) return;
fs::copy_file(src, dst, fs::copy_options::overwrite_existing, ec);
if (ec) return;
// When dst is replaced, the libraries do not all copy the bits.
fs::permissions(dst, s.permissions(), fs::perm_options::replace, ec);
}
copy_file.hpp 16 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/copy-a-file/.
#pragma once
#include <filesystem>
#include <system_error>
// Copies the bytes and the permission bits of the file at src to dst, and
// replaces a file at dst. Sets ec on an error: std::errc::is_a_directory for a
// directory at src or dst, std::errc::invalid_argument when src and dst are
// the same file, or the error of the copy. The function is in a namespace,
// because a call with path arguments also finds std::filesystem::copy_file.
namespace files {
void copy_file(const std::filesystem::path& src, const std::filesystem::path& dst, std::error_code& ec);
} // namespace files
test_copy_file.cpp 130 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/copy-a-file/.
#include <cstdio>
#include <filesystem>
#include <fstream>
#include <iterator>
#include <optional>
#include <string>
#include <system_error>
#include "copy_file.hpp"
namespace fs = std::filesystem;
namespace {
const fs::path dir = "copy_file_tree";
int failures = 0;
void put(const fs::path& p, const std::string& text) { std::ofstream(p, std::ios::binary) << text; }
std::string get(const fs::path& p) {
std::ifstream in(p, std::ios::binary);
return {std::istreambuf_iterator<char>(in), {}};
}
void expect(bool ok, const char* what) {
if (!ok) {
std::fprintf(stderr, "%s\n", what);
++failures;
}
}
void fresh() {
fs::remove_all(dir);
fs::create_directories(dir / "sub");
}
void run_case(const char* name, const char* src, const char* dst, const std::string& src_text,
std::optional<std::string> dst_text) {
fresh();
if (dst_text) put(dir / dst, *dst_text);
put(dir / src, src_text);
std::error_code ec;
files::copy_file(dir / src, dir / dst, ec);
if (ec || get(dir / dst) != src_text || get(dir / src) != src_text) {
std::fprintf(stderr, "%s: %s\n", name, ec.message().c_str());
++failures;
}
}
bool fails(const fs::path& src, const fs::path& dst, std::errc want) {
std::error_code ec;
files::copy_file(src, dst, ec);
return ec == want;
}
void test_errors() {
fresh();
expect(fails(dir / "a.txt", dir / "b.txt", std::errc::no_such_file_or_directory), "missing src");
put(dir / "a.txt", "alpha\n");
expect(fails(dir / "a.txt", dir / "no-such-dir/b.txt", std::errc::no_such_file_or_directory),
"missing dst dir");
expect(fails(dir / "sub", dir / "b.txt", std::errc::is_a_directory), "src dir");
expect(fails(dir / "a.txt", dir / "sub", std::errc::is_a_directory), "dst dir");
expect(fs::is_empty(dir / "sub") && !fs::exists(dir / "b.txt"), "no change");
fs::create_hard_link(dir / "a.txt", dir / "c.txt");
expect(fails(dir / "a.txt", dir / "a.txt", std::errc::invalid_argument), "same path");
expect(fails(dir / "a.txt", dir / "c.txt", std::errc::invalid_argument), "hard link");
expect(get(dir / "a.txt") == "alpha\n", "same file keeps its data");
}
void test_mode() {
fresh();
put(dir / "a.sh", "echo alpha\n");
put(dir / "c.sh", "beta\n");
auto bits = fs::perms::owner_all | fs::perms::group_read | fs::perms::group_exec;
fs::permissions(dir / "a.sh", bits);
fs::permissions(dir / "c.sh", fs::perms::owner_read | fs::perms::owner_write | fs::perms::group_read);
for (const char* name : {"b.sh", "c.sh"}) {
std::error_code ec;
files::copy_file(dir / "a.sh", dir / name, ec);
expect(!ec && fs::status(dir / name).permissions() == bits, name);
}
}
void test_large() {
fresh();
std::string data(5000003, '\0');
for (std::size_t i = 0; i < data.size(); ++i) data[i] = static_cast<char>(i * 7 % 251);
put(dir / "big.bin", data);
std::error_code ec;
files::copy_file(dir / "big.bin", dir / "copy.bin", ec);
expect(!ec && get(dir / "copy.bin") == data, "large");
}
void test_link_at_src() {
fresh();
put(dir / "target.txt", "alpha\n");
fs::create_symlink("target.txt", dir / "link.txt");
std::error_code ec;
files::copy_file(dir / "link.txt", dir / "b.txt", ec);
expect(!ec && fs::is_regular_file(fs::symlink_status(dir / "b.txt")), "link gives a file");
expect(get(dir / "b.txt") == "alpha\n", "link data");
}
} // namespace
int main() {
using namespace std::string_literals;
run_case("copy", "a.txt", "b.txt", "alpha\n", std::nullopt);
run_case("replace-existing", "a.txt", "b.txt", "alpha\n", "beta, a longer text\n");
run_case("empty-file", "a.txt", "b.txt", "", "beta\n");
run_case("other-directory", "a.txt", "sub/a.txt", "alpha\n", std::nullopt);
run_case("name-with-spaces", "my notes.txt", "copy of my notes.txt", "alpha\n", std::nullopt);
run_case("non-ascii-name", "a.txt", "café 日本.txt", "alpha\n", std::nullopt);
run_case("binary-data", "a.bin", "b.bin", "\0\r\nÿ\0"s, std::nullopt);
test_errors();
test_mode();
test_large();
test_link_at_src();
fs::remove_all(dir);
if (failures != 0) {
std::fprintf(stderr, "%d failures\n", failures);
return 1;
}
std::puts("ok");
return 0;
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/copy-a-file/.
import java.io.IOException;
import java.nio.file.FileSystemException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.nio.file.attribute.BasicFileAttributes;
import java.nio.file.attribute.PosixFileAttributeView;
public final class CopyFile {
private CopyFile() {}
/**
* Copies the bytes and the permission bits of the file at src to dst, and replaces a file at dst.
*
* <p>Files.copy copies a directory as a new empty directory, it replaces an empty directory at
* dst, and it does nothing when src and dst are the same file. So the method checks these cases
* first and throws a FileSystemException. With no COPY_ATTRIBUTES, Files.copy does not have to
* copy the permission bits, so the method sets them after the copy.
*/
public static void copy(Path src, Path dst) throws IOException {
BasicFileAttributes s = Files.readAttributes(src, BasicFileAttributes.class);
if (s.isDirectory()) {
throw new FileSystemException(src.toString(), null, "Is a directory");
}
if (Files.isDirectory(dst)) {
throw new FileSystemException(dst.toString(), null, "Is a directory");
}
if (Files.exists(dst) && Files.isSameFile(src, dst)) {
throw new FileSystemException(src.toString(), dst.toString(), "Same file");
}
Files.copy(src, dst, StandardCopyOption.REPLACE_EXISTING);
if (Files.getFileStore(dst).supportsFileAttributeView(PosixFileAttributeView.class)) {
Files.setPosixFilePermissions(dst, Files.getPosixFilePermissions(src));
}
}
}
CopyFileTest.java 127 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/copy-a-file/.
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.FileSystemException;
import java.nio.file.Files;
import java.nio.file.NoSuchFileException;
import java.nio.file.Path;
import java.nio.file.attribute.PosixFilePermissions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
class CopyFileTest {
@TempDir Path dir;
private static byte[] text(String s) {
String t = switch (s) {
case "EMPTY" -> "";
case "BINARY" -> "\0\r\nÿ\0";
default -> s + "\n";
};
return t.getBytes(StandardCharsets.UTF_8);
}
@ParameterizedTest(name = "{0}")
@CsvSource(
delimiter = '|',
nullValues = "NULL",
value = {
"copy | a.txt | b.txt | alpha | NULL",
"replace-existing | a.txt | b.txt | alpha | beta, a longer text",
"empty-file | a.txt | b.txt | EMPTY | beta",
"other-directory | a.txt | sub/a.txt | alpha | NULL",
"name-with-spaces | my notes.txt | copy of my notes.txt | alpha | NULL",
"non-ascii-name | a.txt | café 日本.txt | alpha | NULL",
"binary-data | a.bin | b.bin | BINARY | NULL",
})
void cases(String name, String srcRel, String dstRel, String srcText, String dstText)
throws IOException {
Path src = dir.resolve(srcRel);
Path dst = dir.resolve(dstRel);
Files.createDirectories(dst.getParent());
if (dstText != null) {
Files.write(dst, text(dstText));
}
Files.write(src, text(srcText));
CopyFile.copy(src, dst);
assertArrayEquals(text(srcText), Files.readAllBytes(dst), name);
assertArrayEquals(text(srcText), Files.readAllBytes(src), name);
}
@Test
void missing() throws IOException {
assertThrows(NoSuchFileException.class, () -> CopyFile.copy(dir.resolve("a.txt"), dir.resolve("b.txt")));
Files.writeString(dir.resolve("a.txt"), "alpha\n");
assertThrows(
NoSuchFileException.class,
() -> CopyFile.copy(dir.resolve("a.txt"), dir.resolve("no-such-dir/b.txt")));
}
@Test
void directories() throws IOException {
Path sub = Files.createDirectory(dir.resolve("dir"));
Path src = Files.writeString(dir.resolve("a.txt"), "alpha\n");
FileSystemException e = assertThrows(FileSystemException.class, () -> CopyFile.copy(sub, dir.resolve("b.txt")));
assertEquals("Is a directory", e.getReason());
e = assertThrows(FileSystemException.class, () -> CopyFile.copy(src, sub));
assertEquals("Is a directory", e.getReason());
assertTrue(Files.isDirectory(sub));
try (var entries = Files.list(sub)) {
assertEquals(0, entries.count());
}
assertFalse(Files.exists(dir.resolve("b.txt")));
}
@Test
void sameFile() throws IOException {
Path src = Files.writeString(dir.resolve("a.txt"), "alpha\n");
Path link = Files.createLink(dir.resolve("b.txt"), src);
for (Path dst : new Path[] {src, link}) {
FileSystemException e = assertThrows(FileSystemException.class, () -> CopyFile.copy(src, dst));
assertEquals("Same file", e.getReason());
assertEquals("alpha\n", Files.readString(src));
}
}
@Test
void mode() throws IOException {
Path src = Files.writeString(dir.resolve("a.sh"), "echo alpha\n");
Files.setPosixFilePermissions(src, PosixFilePermissions.fromString("rwxr-x---"));
CopyFile.copy(src, dir.resolve("b.sh"));
assertEquals("rwxr-x---", PosixFilePermissions.toString(Files.getPosixFilePermissions(dir.resolve("b.sh"))));
Path other = Files.writeString(dir.resolve("c.sh"), "beta\n");
Files.setPosixFilePermissions(other, PosixFilePermissions.fromString("rw-r-----"));
CopyFile.copy(src, other);
assertEquals("rwxr-x---", PosixFilePermissions.toString(Files.getPosixFilePermissions(other)));
}
@Test
void largeFile() throws IOException {
byte[] data = new byte[5_000_003];
for (int i = 0; i < data.length; i++) {
data[i] = (byte) ((long) i * 7 % 251);
}
Path src = Files.write(dir.resolve("big.bin"), data);
CopyFile.copy(src, dir.resolve("copy.bin"));
assertArrayEquals(data, Files.readAllBytes(dir.resolve("copy.bin")));
}
@Test
void linkAtSrc() throws IOException {
Files.writeString(dir.resolve("target.txt"), "alpha\n");
Path link = Files.createSymbolicLink(dir.resolve("link.txt"), Path.of("target.txt"));
CopyFile.copy(link, dir.resolve("b.txt"));
assertFalse(Files.isSymbolicLink(dir.resolve("b.txt")));
assertEquals("alpha\n", Files.readString(dir.resolve("b.txt")));
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/copy-a-file/.
// open, read, write, fstat and fchmod are in POSIX, not in ISO C.
#define _POSIX_C_SOURCE 200809L
#include "copy_file.h"
#include <errno.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
// copy_all writes all bytes from in to out. read and write can do less than
// the full count, and a signal can stop them with EINTR, so both are loops.
static int copy_all(int in, int out) {
static char buf[1 << 16];
for (;;) {
ssize_t n = read(in, buf, sizeof buf);
if (n == 0) return 0;
if (n < 0) {
if (errno == EINTR) continue;
return -1;
}
for (ssize_t off = 0; off < n;) {
ssize_t w = write(out, buf + off, (size_t)(n - off));
if (w < 0) {
if (errno == EINTR) continue;
return -1;
}
off += w;
}
}
}
int copy_file(const char *src, const char *dst) {
int in = open(src, O_RDONLY);
if (in < 0) return -1;
struct stat s, d;
int err = 0;
if (fstat(in, &s) != 0) {
err = errno;
} else if (S_ISDIR(s.st_mode)) {
err = EISDIR;
} else if (stat(dst, &d) == 0) {
// O_TRUNC on the same file makes it empty before the copy reads it.
if (S_ISDIR(d.st_mode)) err = EISDIR;
else if (d.st_dev == s.st_dev && d.st_ino == s.st_ino) err = EINVAL;
}
if (err != 0) {
close(in);
errno = err;
return -1;
}
mode_t mode = s.st_mode & 07777;
int out = open(dst, O_WRONLY | O_CREAT | O_TRUNC, mode);
if (out < 0) {
err = errno;
close(in);
errno = err;
return -1;
}
// The mode of open is used only for a new file, and the umask changes
// it, so fchmod sets the bits.
if (copy_all(in, out) != 0 || fchmod(out, mode) != 0) err = errno;
close(in);
// A write error can come only at the close, so its result is checked.
if (close(out) != 0 && err == 0) err = errno;
if (err != 0) {
errno = err;
return -1;
}
return 0;
}
copy_file.h 13 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/copy-a-file/.
#ifndef COPY_FILE_H
#define COPY_FILE_H
// copy_file copies the bytes and the permission bits of the file at src to
// dst, and replaces a file at dst. It returns 0, or -1 with errno: ENOENT,
// EISDIR for a directory at src or dst, EINVAL when src and dst are the same
// file, or the error of open, read, write or close.
int copy_file(const char *src, const char *dst);
#endif
test_copy_file.c 150 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/copy-a-file/.
// symlink, link, lstat and getpid are in POSIX.1-2008, not in ISO C.
#define _POSIX_C_SOURCE 200809L
#include "copy_file.h"
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <unistd.h>
static const char *dir = "copy_file_tree";
static int failures = 0;
static char *at(char *buf, const char *name) {
snprintf(buf, 256, "%s/%s", dir, name);
return buf;
}
static void put(const char *name, const char *data, size_t n) {
char p[256];
FILE *f = fopen(at(p, name), "wb");
if (f == NULL || fwrite(data, 1, n, f) != n || fclose(f) != 0) exit(2);
}
// get reads the file into a buffer and returns its size, or -1.
static long get(const char *name, char *data, size_t cap) {
char p[256];
FILE *f = fopen(at(p, name), "rb");
if (f == NULL) return -1;
size_t n = fread(data, 1, cap, f);
fclose(f);
return (long)n;
}
static void expect(int ok, const char *what) {
if (!ok) {
fprintf(stderr, "%s\n", what);
failures++;
}
}
static void fresh(void) {
if (system("rm -rf copy_file_tree") != 0 || mkdir(dir, 0755) != 0) exit(2);
}
static int same(const char *name, const char *want, size_t n) {
char data[64];
return get(name, data, sizeof data) == (long)n && memcmp(data, want, n) == 0;
}
static void run_case(const char *name, const char *src, const char *dst, const char *src_text,
size_t n, const char *dst_text) {
char s[256], d[256];
fresh();
if (strchr(dst, '/') != NULL && mkdir(at(d, "sub"), 0755) != 0) exit(2);
if (dst_text != NULL) put(dst, dst_text, strlen(dst_text));
put(src, src_text, n);
expect(copy_file(at(s, src), at(d, dst)) == 0, name);
expect(same(dst, src_text, n), name);
expect(same(src, src_text, n), name);
}
static void test_errors(void) {
char s[256], d[256];
fresh();
errno = 0;
expect(copy_file(at(s, "a.txt"), at(d, "b.txt")) == -1 && errno == ENOENT, "missing src");
put("a.txt", "alpha\n", 6);
errno = 0;
expect(copy_file(at(s, "a.txt"), at(d, "no-such-dir/b.txt")) == -1 && errno == ENOENT,
"missing dst dir");
if (mkdir(at(d, "dir"), 0755) != 0) exit(2);
errno = 0;
expect(copy_file(at(s, "dir"), at(d, "b.txt")) == -1 && errno == EISDIR, "src dir");
errno = 0;
expect(copy_file(at(s, "a.txt"), at(d, "dir")) == -1 && errno == EISDIR, "dst dir");
struct stat st;
expect(lstat(at(d, "b.txt"), &st) != 0, "no b.txt");
if (link(at(s, "a.txt"), at(d, "c.txt")) != 0) exit(2);
errno = 0;
expect(copy_file(at(s, "a.txt"), at(d, "a.txt")) == -1 && errno == EINVAL, "same path");
errno = 0;
expect(copy_file(at(s, "a.txt"), at(d, "c.txt")) == -1 && errno == EINVAL, "hard link");
expect(same("a.txt", "alpha\n", 6), "same file keeps its data");
}
static void test_mode(void) {
char s[256], d[256];
struct stat st;
fresh();
put("a.sh", "echo alpha\n", 11);
put("c.sh", "beta\n", 5);
if (chmod(at(s, "a.sh"), 0750) != 0 || chmod(at(d, "c.sh"), 0640) != 0) exit(2);
expect(copy_file(at(s, "a.sh"), at(d, "b.sh")) == 0, "mode new");
expect(stat(at(d, "b.sh"), &st) == 0 && (st.st_mode & 07777) == 0750, "mode new bits");
expect(copy_file(at(s, "a.sh"), at(d, "c.sh")) == 0, "mode replace");
expect(stat(at(d, "c.sh"), &st) == 0 && (st.st_mode & 07777) == 0750, "mode replace bits");
}
static void test_large(void) {
enum { N = 5000003 };
char s[256], d[256];
char *data = malloc(N), *got = malloc(N + 1);
if (data == NULL || got == NULL) exit(2);
for (long i = 0; i < N; i++) data[i] = (char)(i * 7 % 251);
fresh();
put("big.bin", data, N);
expect(copy_file(at(s, "big.bin"), at(d, "copy.bin")) == 0, "large");
expect(get("copy.bin", got, N + 1) == N && memcmp(got, data, N) == 0, "large data");
free(data);
free(got);
}
static void test_link_at_src(void) {
char s[256], d[256];
struct stat st;
fresh();
put("target.txt", "alpha\n", 6);
if (symlink("target.txt", at(s, "link.txt")) != 0) exit(2);
expect(copy_file(at(s, "link.txt"), at(d, "b.txt")) == 0, "link");
expect(lstat(at(d, "b.txt"), &st) == 0 && S_ISREG(st.st_mode), "link gives a file");
expect(same("b.txt", "alpha\n", 6), "link data");
}
int main(void) {
run_case("copy", "a.txt", "b.txt", "alpha\n", 6, NULL);
run_case("replace-existing", "a.txt", "b.txt", "alpha\n", 6, "beta, a longer text\n");
run_case("empty-file", "a.txt", "b.txt", "", 0, "beta\n");
run_case("other-directory", "a.txt", "sub/a.txt", "alpha\n", 6, NULL);
run_case("name-with-spaces", "my notes.txt", "copy of my notes.txt", "alpha\n", 6, NULL);
run_case("non-ascii-name", "a.txt", "caf\xc3\xa9 \xe6\x97\xa5\xe6\x9c\xac.txt", "alpha\n", 6,
NULL);
run_case("binary-data", "a.bin", "b.bin", "\0\r\n\xc3\xbf\0", 6, NULL);
test_errors();
test_mode();
test_large();
test_link_at_src();
if (system("rm -rf copy_file_tree") != 0) failures++;
if (failures != 0) {
fprintf(stderr, "%d failures\n", failures);
return 1;
}
puts("ok");
return 0;
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/copy-a-file/.
public static class CopyFile
{
/// <summary>
/// Copies the bytes and the permission bits of the file at src to dst, and
/// replaces a file at dst. File.Copy with overwrite true does the copy. A
/// directory at src or dst gives an IOException. On Unix, the code sets the
/// permission bits of dst after the copy, so that they are also correct when
/// the copy replaces a file. Each other error, for example
/// FileNotFoundException, goes to the caller.
/// </summary>
public static void Copy(string src, string dst)
{
if (Directory.Exists(src))
{
throw new IOException($"Is a directory: '{src}'");
}
if (Directory.Exists(dst))
{
throw new IOException($"Is a directory: '{dst}'");
}
File.Copy(src, dst, overwrite: true);
if (!OperatingSystem.IsWindows())
{
File.SetUnixFileMode(dst, File.GetUnixFileMode(src));
}
}
}
CopyFileTests.cs 135 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/copy-a-file/.
using System.Text;
using Xunit;
public sealed class CopyFileTests : IDisposable
{
private readonly string dir = Directory.CreateTempSubdirectory("copy-file-").FullName;
public void Dispose() => Directory.Delete(dir, recursive: true);
// name, src, dst, content of src, content of dst or null
public static TheoryData<string, string, string, string, string?> Cases => new()
{
{ "copy", "a.txt", "b.txt", "alpha\n", null },
{ "replace-existing", "a.txt", "b.txt", "alpha\n", "beta, a longer text\n" },
{ "empty-file", "a.txt", "b.txt", "", "beta\n" },
{ "other-directory", "a.txt", "sub/a.txt", "alpha\n", null },
{ "name-with-spaces", "my notes.txt", "copy of my notes.txt", "alpha\n", null },
{ "non-ascii-name", "a.txt", "café 日本.txt", "alpha\n", null },
{ "binary-data", "a.bin", "b.bin", "\0\r\nÿ\0", null },
};
[Theory]
[MemberData(nameof(Cases))]
public void Copies(string name, string srcRel, string dstRel, string srcText, string? dstText)
{
string src = Path.Combine(dir, srcRel), dst = Path.Combine(dir, dstRel);
Directory.CreateDirectory(Path.GetDirectoryName(dst)!);
byte[] want = Encoding.UTF8.GetBytes(srcText);
if (dstText != null)
{
File.WriteAllBytes(dst, Encoding.UTF8.GetBytes(dstText));
}
File.WriteAllBytes(src, want);
CopyFile.Copy(src, dst);
Assert.True(want.AsSpan().SequenceEqual(File.ReadAllBytes(dst)), name);
Assert.True(want.AsSpan().SequenceEqual(File.ReadAllBytes(src)), name);
}
[Fact]
public void Missing()
{
string src = Path.Combine(dir, "a.txt");
Assert.Throws<FileNotFoundException>(() => CopyFile.Copy(src, Path.Combine(dir, "b.txt")));
File.WriteAllText(src, "alpha\n");
Assert.Throws<DirectoryNotFoundException>(() => CopyFile.Copy(src, Path.Combine(dir, "no-such-dir", "b.txt")));
}
[Fact]
public void Directories()
{
string sub = Directory.CreateDirectory(Path.Combine(dir, "dir")).FullName;
string src = Path.Combine(dir, "a.txt");
File.WriteAllText(src, "alpha\n");
Assert.Throws<IOException>(() => CopyFile.Copy(sub, Path.Combine(dir, "b.txt")));
Assert.Throws<IOException>(() => CopyFile.Copy(src, sub));
Assert.Empty(Directory.GetFileSystemEntries(sub));
Assert.False(File.Exists(Path.Combine(dir, "b.txt")));
}
[Fact]
public void SamePath()
{
string src = Path.Combine(dir, "a.txt");
File.WriteAllText(src, "alpha\n");
Assert.Throws<IOException>(() => CopyFile.Copy(src, src));
Assert.Equal("alpha\n", File.ReadAllText(src));
}
[Fact]
public void HardLink()
{
if (OperatingSystem.IsWindows())
{
return;
}
string src = Path.Combine(dir, "a.txt"), link = Path.Combine(dir, "b.txt");
File.WriteAllText(src, "alpha\n");
using (var ln = System.Diagnostics.Process.Start("ln", new[] { src, link }))
{
ln.WaitForExit();
Assert.Equal(0, ln.ExitCode);
}
Assert.Throws<IOException>(() => CopyFile.Copy(src, link));
Assert.Equal("alpha\n", File.ReadAllText(src));
}
[Fact]
public void Mode()
{
if (OperatingSystem.IsWindows())
{
return;
}
const UnixFileMode bits = UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute
| UnixFileMode.GroupRead | UnixFileMode.GroupExecute;
string src = Path.Combine(dir, "a.sh"), other = Path.Combine(dir, "c.sh");
File.WriteAllText(src, "echo alpha\n");
File.SetUnixFileMode(src, bits);
File.WriteAllText(other, "beta\n");
File.SetUnixFileMode(other, UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.GroupRead);
foreach (string dst in new[] { Path.Combine(dir, "b.sh"), other })
{
CopyFile.Copy(src, dst);
Assert.Equal(bits, File.GetUnixFileMode(dst));
}
}
[Fact]
public void LargeFile()
{
byte[] data = new byte[5_000_003];
for (int i = 0; i < data.Length; i++)
{
data[i] = (byte)((long)i * 7 % 251);
}
string src = Path.Combine(dir, "big.bin"), dst = Path.Combine(dir, "copy.bin");
File.WriteAllBytes(src, data);
CopyFile.Copy(src, dst);
Assert.True(data.AsSpan().SequenceEqual(File.ReadAllBytes(dst)));
}
[Fact]
public void LinkAtSrc()
{
File.WriteAllText(Path.Combine(dir, "target.txt"), "alpha\n");
File.CreateSymbolicLink(Path.Combine(dir, "link.txt"), "target.txt");
string dst = Path.Combine(dir, "b.txt");
CopyFile.Copy(Path.Combine(dir, "link.txt"), dst);
Assert.Null(new FileInfo(dst).LinkTarget);
Assert.Equal("alpha\n", File.ReadAllText(dst));
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/copy-a-file/.
import { chmod, copyFile as fsCopyFile, stat } from "node:fs/promises";
function fail(code, message, path) {
const err = new Error(`${code}: ${message}, copy '${path}'`);
err.code = code;
err.path = path;
return err;
}
/**
* Copies the bytes and the permission bits of the file at src to dst, and
* replaces a file at dst. fs.copyFile uses the fast copy call of the
* platform, but it copies a file onto itself with no error, so the code
* compares the device and inode numbers first. It also gives the error
* EISDIR for a directory at src or dst. Each error is thrown.
*/
export async function copyFile(src, dst) {
const s = await stat(src);
if (s.isDirectory()) {
throw fail("EISDIR", "illegal operation on a directory", src);
}
let d = null;
try {
d = await stat(dst);
} catch (err) {
if (err.code !== "ENOENT") {
throw err;
}
}
if (d !== null && d.isDirectory()) {
throw fail("EISDIR", "illegal operation on a directory", dst);
}
if (d !== null && d.dev === s.dev && d.ino === s.ino) {
throw fail("ESAMEFILE", "src and dst are the same file", dst);
}
await fsCopyFile(src, dst);
await chmod(dst, s.mode & 0o7777);
}
copyFile.test.js 108 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/copy-a-file/.
import { test } from "node:test";
import assert from "node:assert/strict";
import { existsSync, lstatSync, statSync } from "node:fs";
import { chmod, link, mkdir, mkdtemp, readdir, readFile, rm, symlink, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { dirname, join } from "node:path";
import { copyFile } from "./copyFile.js";
async function withDir(fn) {
const dir = await mkdtemp(join(tmpdir(), "copy-file-"));
try {
await fn(dir);
} finally {
await rm(dir, { recursive: true, force: true });
}
}
// name: [src, dst, content of src, content of dst or null]
const cases = [
["copy", "a.txt", "b.txt", "alpha\n", null],
["replace-existing", "a.txt", "b.txt", "alpha\n", "beta, a longer text\n"],
["empty-file", "a.txt", "b.txt", "", "beta\n"],
["other-directory", "a.txt", "sub/a.txt", "alpha\n", null],
["name-with-spaces", "my notes.txt", "copy of my notes.txt", "alpha\n", null],
["non-ascii-name", "a.txt", "café 日本.txt", "alpha\n", null],
["binary-data", "a.bin", "b.bin", "\0\r\nÿ\0", null],
];
for (const [name, srcRel, dstRel, srcText, dstText] of cases) {
test(name, () =>
withDir(async (dir) => {
const src = join(dir, srcRel);
const dst = join(dir, dstRel);
await mkdir(dirname(dst), { recursive: true });
if (dstText !== null) {
await writeFile(dst, dstText);
}
await writeFile(src, srcText);
await copyFile(src, dst);
assert.deepEqual(await readFile(dst), Buffer.from(srcText));
assert.deepEqual(await readFile(src), Buffer.from(srcText));
}));
}
test("missing", () =>
withDir(async (dir) => {
await assert.rejects(copyFile(join(dir, "a.txt"), join(dir, "b.txt")), { code: "ENOENT" });
await writeFile(join(dir, "a.txt"), "alpha\n");
await assert.rejects(copyFile(join(dir, "a.txt"), join(dir, "no-such-dir", "b.txt")), { code: "ENOENT" });
}));
test("directories", () =>
withDir(async (dir) => {
await mkdir(join(dir, "dir"));
await writeFile(join(dir, "a.txt"), "alpha\n");
await assert.rejects(copyFile(join(dir, "dir"), join(dir, "b.txt")), { code: "EISDIR" });
await assert.rejects(copyFile(join(dir, "a.txt"), join(dir, "dir")), { code: "EISDIR" });
assert.deepEqual(await readdir(join(dir, "dir")), []);
assert.equal(existsSync(join(dir, "b.txt")), false);
}));
test("same file", () =>
withDir(async (dir) => {
const src = join(dir, "a.txt");
await writeFile(src, "alpha\n");
await link(src, join(dir, "b.txt"));
for (const dst of [src, join(dir, "b.txt")]) {
await assert.rejects(copyFile(src, dst), { code: "ESAMEFILE" });
assert.equal(await readFile(src, "utf8"), "alpha\n");
}
}));
test("mode", () =>
withDir(async (dir) => {
const src = join(dir, "a.sh");
await writeFile(src, "echo alpha\n");
await chmod(src, 0o750);
await copyFile(src, join(dir, "b.sh"));
assert.equal(statSync(join(dir, "b.sh")).mode & 0o7777, 0o750);
const other = join(dir, "c.sh");
await writeFile(other, "beta\n");
await chmod(other, 0o640);
await copyFile(src, other);
assert.equal(statSync(other).mode & 0o7777, 0o750);
}));
test("large file", () =>
withDir(async (dir) => {
const data = Buffer.alloc(5_000_003);
for (let i = 0; i < data.length; i++) {
data[i] = (i * 7) % 251;
}
await writeFile(join(dir, "big.bin"), data);
await copyFile(join(dir, "big.bin"), join(dir, "copy.bin"));
assert.ok(data.equals(await readFile(join(dir, "copy.bin"))));
}));
test("link at src", () =>
withDir(async (dir) => {
await writeFile(join(dir, "target.txt"), "alpha\n");
await symlink("target.txt", join(dir, "link.txt"));
await copyFile(join(dir, "link.txt"), join(dir, "b.txt"));
assert.equal(lstatSync(join(dir, "b.txt")).isSymbolicLink(), false);
assert.equal(await readFile(join(dir, "b.txt"), "utf8"), "alpha\n");
}));
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/copy-a-file/.
import { chmod, copyFile as fsCopyFile, stat } from "node:fs/promises";
function fail(code: string, message: string, path: string): NodeJS.ErrnoException {
const err: NodeJS.ErrnoException = new Error(`${code}: ${message}, copy '${path}'`);
err.code = code;
err.path = path;
return err;
}
/**
* Copies the bytes and the permission bits of the file at src to dst, and
* replaces a file at dst. fs.copyFile uses the fast copy call of the
* platform, but it copies a file onto itself with no error, so the code
* compares the device and inode numbers first. It also gives the error
* EISDIR for a directory at src or dst. Each error is thrown.
*/
export async function copyFile(src: string, dst: string): Promise<void> {
const s = await stat(src);
if (s.isDirectory()) {
throw fail("EISDIR", "illegal operation on a directory", src);
}
let d: Awaited<ReturnType<typeof stat>> | null = null;
try {
d = await stat(dst);
} catch (err) {
if ((err as NodeJS.ErrnoException).code !== "ENOENT") {
throw err;
}
}
if (d !== null && d.isDirectory()) {
throw fail("EISDIR", "illegal operation on a directory", dst);
}
if (d !== null && d.dev === s.dev && d.ino === s.ino) {
throw fail("ESAMEFILE", "src and dst are the same file", dst);
}
await fsCopyFile(src, dst);
await chmod(dst, s.mode & 0o7777);
}
copyFile.test.ts 108 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/copy-a-file/.
import { test } from "node:test";
import assert from "node:assert/strict";
import { existsSync, lstatSync, statSync } from "node:fs";
import { chmod, link, mkdir, mkdtemp, readdir, readFile, rm, symlink, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { dirname, join } from "node:path";
import { copyFile } from "./copyFile.ts";
async function withDir(fn: (dir: string) => Promise<void>): Promise<void> {
const dir = await mkdtemp(join(tmpdir(), "copy-file-"));
try {
await fn(dir);
} finally {
await rm(dir, { recursive: true, force: true });
}
}
// name: [src, dst, content of src, content of dst or null]
const cases: [string, string, string, string, string | null][] = [
["copy", "a.txt", "b.txt", "alpha\n", null],
["replace-existing", "a.txt", "b.txt", "alpha\n", "beta, a longer text\n"],
["empty-file", "a.txt", "b.txt", "", "beta\n"],
["other-directory", "a.txt", "sub/a.txt", "alpha\n", null],
["name-with-spaces", "my notes.txt", "copy of my notes.txt", "alpha\n", null],
["non-ascii-name", "a.txt", "café 日本.txt", "alpha\n", null],
["binary-data", "a.bin", "b.bin", "\0\r\nÿ\0", null],
];
for (const [name, srcRel, dstRel, srcText, dstText] of cases) {
test(name, () =>
withDir(async (dir) => {
const src = join(dir, srcRel);
const dst = join(dir, dstRel);
await mkdir(dirname(dst), { recursive: true });
if (dstText !== null) {
await writeFile(dst, dstText);
}
await writeFile(src, srcText);
await copyFile(src, dst);
assert.deepEqual(await readFile(dst), Buffer.from(srcText));
assert.deepEqual(await readFile(src), Buffer.from(srcText));
}));
}
test("missing", () =>
withDir(async (dir) => {
await assert.rejects(copyFile(join(dir, "a.txt"), join(dir, "b.txt")), { code: "ENOENT" });
await writeFile(join(dir, "a.txt"), "alpha\n");
await assert.rejects(copyFile(join(dir, "a.txt"), join(dir, "no-such-dir", "b.txt")), { code: "ENOENT" });
}));
test("directories", () =>
withDir(async (dir) => {
await mkdir(join(dir, "dir"));
await writeFile(join(dir, "a.txt"), "alpha\n");
await assert.rejects(copyFile(join(dir, "dir"), join(dir, "b.txt")), { code: "EISDIR" });
await assert.rejects(copyFile(join(dir, "a.txt"), join(dir, "dir")), { code: "EISDIR" });
assert.deepEqual(await readdir(join(dir, "dir")), []);
assert.equal(existsSync(join(dir, "b.txt")), false);
}));
test("same file", () =>
withDir(async (dir) => {
const src = join(dir, "a.txt");
await writeFile(src, "alpha\n");
await link(src, join(dir, "b.txt"));
for (const dst of [src, join(dir, "b.txt")]) {
await assert.rejects(copyFile(src, dst), { code: "ESAMEFILE" });
assert.equal(await readFile(src, "utf8"), "alpha\n");
}
}));
test("mode", () =>
withDir(async (dir) => {
const src = join(dir, "a.sh");
await writeFile(src, "echo alpha\n");
await chmod(src, 0o750);
await copyFile(src, join(dir, "b.sh"));
assert.equal(statSync(join(dir, "b.sh")).mode & 0o7777, 0o750);
const other = join(dir, "c.sh");
await writeFile(other, "beta\n");
await chmod(other, 0o640);
await copyFile(src, other);
assert.equal(statSync(other).mode & 0o7777, 0o750);
}));
test("large file", () =>
withDir(async (dir) => {
const data = Buffer.alloc(5_000_003);
for (let i = 0; i < data.length; i++) {
data[i] = (i * 7) % 251;
}
await writeFile(join(dir, "big.bin"), data);
await copyFile(join(dir, "big.bin"), join(dir, "copy.bin"));
assert.ok(data.equals(await readFile(join(dir, "copy.bin"))));
}));
test("link at src", () =>
withDir(async (dir) => {
await writeFile(join(dir, "target.txt"), "alpha\n");
await symlink("target.txt", join(dir, "link.txt"));
await copyFile(join(dir, "link.txt"), join(dir, "b.txt"));
assert.equal(lstatSync(join(dir, "b.txt")).isSymbolicLink(), false);
assert.equal(await readFile(join(dir, "b.txt"), "utf8"), "alpha\n");
}));
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/copy-a-file/.
// Package copyfile copies a file.
package copyfile
import (
"errors"
"io"
"io/fs"
"os"
"syscall"
)
// ErrSameFile is the error when src and dst name the same file.
var ErrSameFile = errors.New("src and dst are the same file")
// CopyFile copies the bytes and the permission bits of the file at src to
// dst, and replaces a file at dst. Go has no function that copies a file, so
// the code opens both files and calls io.Copy. On Linux, io.Copy to an
// *os.File uses copy_file_range or sendfile. The code checks first that dst
// is not a directory and not the same file as src, because O_TRUNC on the
// same file makes it empty. The error of Close is returned, because a write
// error can come only at the close.
func CopyFile(src, dst string) (err error) {
in, err := os.Open(src)
if err != nil {
return err
}
defer in.Close()
s, err := in.Stat()
if err != nil {
return err
}
if s.IsDir() {
return &fs.PathError{Op: "copy", Path: src, Err: syscall.EISDIR}
}
if d, err := os.Stat(dst); err == nil {
if d.IsDir() {
return &fs.PathError{Op: "copy", Path: dst, Err: syscall.EISDIR}
}
if os.SameFile(s, d) {
return &fs.PathError{Op: "copy", Path: dst, Err: ErrSameFile}
}
}
out, err := os.OpenFile(dst, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, s.Mode().Perm())
if err != nil {
return err
}
defer func() {
if cerr := out.Close(); err == nil {
err = cerr
}
}()
if _, err = io.Copy(out, in); err != nil {
return err
}
// The mode of OpenFile is used only for a new file, and the umask
// changes it, so the code sets the bits again.
return out.Chmod(s.Mode().Perm())
}
copy_file_test.go 148 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/copy-a-file/.
package copyfile
import (
"bytes"
"errors"
"io/fs"
"os"
"path/filepath"
"syscall"
"testing"
)
func must(t *testing.T, err error) {
t.Helper()
if err != nil {
t.Fatal(err)
}
}
func TestCases(t *testing.T) {
// name: src, dst, content of src, content of dst ("-" for no file)
cases := []struct{ name, src, dst, srcText, dstText string }{
{"copy", "a.txt", "b.txt", "alpha\n", "-"},
{"replace-existing", "a.txt", "b.txt", "alpha\n", "beta, a longer text\n"},
{"empty-file", "a.txt", "b.txt", "", "beta\n"},
{"other-directory", "a.txt", "sub/a.txt", "alpha\n", "-"},
{"name-with-spaces", "my notes.txt", "copy of my notes.txt", "alpha\n", "-"},
{"non-ascii-name", "a.txt", "café 日本.txt", "alpha\n", "-"},
{"binary-data", "a.bin", "b.bin", "\x00\r\nÿ\x00", "-"},
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
dir := t.TempDir()
src, dst := filepath.Join(dir, c.src), filepath.Join(dir, c.dst)
must(t, os.MkdirAll(filepath.Dir(dst), 0o755))
if c.dstText != "-" {
must(t, os.WriteFile(dst, []byte(c.dstText), 0o644))
}
must(t, os.WriteFile(src, []byte(c.srcText), 0o644))
must(t, CopyFile(src, dst))
for _, p := range []string{dst, src} {
got, err := os.ReadFile(p)
must(t, err)
if string(got) != c.srcText {
t.Errorf("%s: got %q, want %q", p, got, c.srcText)
}
}
})
}
}
func TestMissing(t *testing.T) {
dir := t.TempDir()
src := filepath.Join(dir, "a.txt")
if err := CopyFile(src, filepath.Join(dir, "b.txt")); !errors.Is(err, fs.ErrNotExist) {
t.Errorf("missing src: got %v", err)
}
must(t, os.WriteFile(src, []byte("alpha\n"), 0o644))
if err := CopyFile(src, filepath.Join(dir, "no-such-dir", "b.txt")); !errors.Is(err, fs.ErrNotExist) {
t.Errorf("missing dst dir: got %v", err)
}
}
func TestDirectories(t *testing.T) {
dir := t.TempDir()
sub, src := filepath.Join(dir, "dir"), filepath.Join(dir, "a.txt")
must(t, os.Mkdir(sub, 0o755))
must(t, os.WriteFile(src, []byte("alpha\n"), 0o644))
if err := CopyFile(sub, filepath.Join(dir, "b.txt")); !errors.Is(err, syscall.EISDIR) {
t.Errorf("src dir: got %v", err)
}
if err := CopyFile(src, sub); !errors.Is(err, syscall.EISDIR) {
t.Errorf("dst dir: got %v", err)
}
if entries, _ := os.ReadDir(sub); len(entries) != 0 {
t.Errorf("dir has %d entries", len(entries))
}
if _, err := os.Lstat(filepath.Join(dir, "b.txt")); !errors.Is(err, fs.ErrNotExist) {
t.Errorf("b.txt: got %v", err)
}
}
func TestSameFile(t *testing.T) {
dir := t.TempDir()
src, link := filepath.Join(dir, "a.txt"), filepath.Join(dir, "b.txt")
must(t, os.WriteFile(src, []byte("alpha\n"), 0o644))
must(t, os.Link(src, link))
for _, dst := range []string{src, link} {
if err := CopyFile(src, dst); !errors.Is(err, ErrSameFile) {
t.Errorf("%s: got %v", dst, err)
}
if got, _ := os.ReadFile(src); string(got) != "alpha\n" {
t.Errorf("%s: src is now %q", dst, got)
}
}
}
func TestMode(t *testing.T) {
dir := t.TempDir()
src, dst, other := filepath.Join(dir, "a.sh"), filepath.Join(dir, "b.sh"), filepath.Join(dir, "c.sh")
must(t, os.WriteFile(src, []byte("echo alpha\n"), 0o644))
must(t, os.Chmod(src, 0o750))
must(t, os.WriteFile(other, []byte("beta\n"), 0o644))
must(t, os.Chmod(other, 0o640))
for _, p := range []string{dst, other} {
must(t, CopyFile(src, p))
info, err := os.Stat(p)
must(t, err)
if info.Mode().Perm() != 0o750 {
t.Errorf("%s: mode %o", p, info.Mode().Perm())
}
}
}
func TestLargeFile(t *testing.T) {
dir := t.TempDir()
data := make([]byte, 5_000_003)
for i := range data {
data[i] = byte(i * 7 % 251)
}
src, dst := filepath.Join(dir, "big.bin"), filepath.Join(dir, "copy.bin")
must(t, os.WriteFile(src, data, 0o644))
must(t, CopyFile(src, dst))
got, err := os.ReadFile(dst)
must(t, err)
if !bytes.Equal(got, data) {
t.Errorf("the copy has %d bytes and is not the same", len(got))
}
}
func TestLinkAtSrc(t *testing.T) {
dir := t.TempDir()
must(t, os.WriteFile(filepath.Join(dir, "target.txt"), []byte("alpha\n"), 0o644))
must(t, os.Symlink("target.txt", filepath.Join(dir, "link.txt")))
dst := filepath.Join(dir, "b.txt")
must(t, CopyFile(filepath.Join(dir, "link.txt"), dst))
info, err := os.Lstat(dst)
must(t, err)
if info.Mode()&fs.ModeSymlink != 0 {
t.Error("the copy is a link")
}
if got, _ := os.ReadFile(dst); string(got) != "alpha\n" {
t.Errorf("got %q", got)
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/copy-a-file/.
use std::fs;
use std::io;
use std::path::Path;
/// Copies the bytes and the permission bits of the file at `src` to `dst`,
/// and replaces a file at `dst`.
///
/// `fs::copy` copies the permission bits, and on Linux it uses
/// copy_file_range. But it opens `dst` with O_TRUNC, so a copy of a file
/// onto itself makes the file empty. So the function compares the device and
/// inode numbers first, and gives an error of kind `InvalidInput` for the
/// same file. A directory at `src` or `dst` gives `IsADirectory`.
pub fn copy_file(src: &Path, dst: &Path) -> io::Result<()> {
let s = fs::metadata(src)?;
if s.is_dir() {
return Err(io::Error::new(io::ErrorKind::IsADirectory, "src is a directory"));
}
match fs::metadata(dst) {
Ok(d) if d.is_dir() => {
return Err(io::Error::new(io::ErrorKind::IsADirectory, "dst is a directory"));
}
Ok(d) if same_file(&s, &d) => {
return Err(io::Error::new(io::ErrorKind::InvalidInput, "src and dst are the same file"));
}
_ => {}
}
fs::copy(src, dst)?;
Ok(())
}
#[cfg(unix)]
fn same_file(a: &fs::Metadata, b: &fs::Metadata) -> bool {
use std::os::unix::fs::MetadataExt;
a.dev() == b.dev() && a.ino() == b.ino()
}
#[cfg(not(unix))]
fn same_file(_: &fs::Metadata, _: &fs::Metadata) -> bool {
false
}
tests/copy_file_test.rs 115 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/copy-a-file/.
use std::fs;
use std::io::ErrorKind;
use std::os::unix::fs::{symlink, PermissionsExt};
use std::path::PathBuf;
use algo_copy_a_file::copy_file;
/// Returns a new, empty directory for one test.
fn new_dir(name: &str) -> PathBuf {
let dir = std::env::temp_dir().join(format!("copy-file-{}-{name}", std::process::id()));
let _ = fs::remove_dir_all(&dir);
fs::create_dir_all(&dir).unwrap();
dir
}
#[test]
fn cases() {
for (name, src, dst, src_text, dst_text) in [
("copy", "a.txt", "b.txt", "alpha\n", None),
("replace-existing", "a.txt", "b.txt", "alpha\n", Some("beta, a longer text\n")),
("empty-file", "a.txt", "b.txt", "", Some("beta\n")),
("other-directory", "a.txt", "sub/a.txt", "alpha\n", None),
("name-with-spaces", "my notes.txt", "copy of my notes.txt", "alpha\n", None),
("non-ascii-name", "a.txt", "café 日本.txt", "alpha\n", None),
("binary-data", "a.bin", "b.bin", "\0\r\nÿ\0", None),
] {
let dir = new_dir(name);
let (src, dst) = (dir.join(src), dir.join(dst));
fs::create_dir_all(dst.parent().unwrap()).unwrap();
if let Some(t) = dst_text {
fs::write(&dst, t).unwrap();
}
fs::write(&src, src_text).unwrap();
copy_file(&src, &dst).unwrap();
assert_eq!(fs::read(&dst).unwrap(), src_text.as_bytes(), "{name}");
assert_eq!(fs::read(&src).unwrap(), src_text.as_bytes(), "{name}");
fs::remove_dir_all(&dir).unwrap();
}
}
#[test]
fn missing() {
let dir = new_dir("missing");
let src = dir.join("a.txt");
assert_eq!(copy_file(&src, &dir.join("b.txt")).unwrap_err().kind(), ErrorKind::NotFound);
fs::write(&src, "alpha\n").unwrap();
let err = copy_file(&src, &dir.join("no-such-dir/b.txt")).unwrap_err();
assert_eq!(err.kind(), ErrorKind::NotFound);
fs::remove_dir_all(&dir).unwrap();
}
#[test]
fn directories() {
let dir = new_dir("directories");
let (sub, src) = (dir.join("dir"), dir.join("a.txt"));
fs::create_dir(&sub).unwrap();
fs::write(&src, "alpha\n").unwrap();
assert_eq!(copy_file(&sub, &dir.join("b.txt")).unwrap_err().kind(), ErrorKind::IsADirectory);
assert_eq!(copy_file(&src, &sub).unwrap_err().kind(), ErrorKind::IsADirectory);
assert_eq!(fs::read_dir(&sub).unwrap().count(), 0);
assert!(fs::symlink_metadata(dir.join("b.txt")).is_err());
fs::remove_dir_all(&dir).unwrap();
}
#[test]
fn same_file() {
let dir = new_dir("same");
let (src, link) = (dir.join("a.txt"), dir.join("b.txt"));
fs::write(&src, "alpha\n").unwrap();
fs::hard_link(&src, &link).unwrap();
for dst in [&src, &link] {
assert_eq!(copy_file(&src, dst).unwrap_err().kind(), ErrorKind::InvalidInput);
assert_eq!(fs::read_to_string(&src).unwrap(), "alpha\n");
}
fs::remove_dir_all(&dir).unwrap();
}
#[test]
fn mode() {
let dir = new_dir("mode");
let (src, dst, other) = (dir.join("a.sh"), dir.join("b.sh"), dir.join("c.sh"));
fs::write(&src, "echo alpha\n").unwrap();
fs::set_permissions(&src, fs::Permissions::from_mode(0o750)).unwrap();
fs::write(&other, "beta\n").unwrap();
fs::set_permissions(&other, fs::Permissions::from_mode(0o640)).unwrap();
for p in [&dst, &other] {
copy_file(&src, p).unwrap();
assert_eq!(fs::metadata(p).unwrap().permissions().mode() & 0o7777, 0o750);
}
fs::remove_dir_all(&dir).unwrap();
}
#[test]
fn large_file() {
let dir = new_dir("large");
let data: Vec<u8> = (0..5_000_003u64).map(|i| (i * 7 % 251) as u8).collect();
fs::write(dir.join("big.bin"), &data).unwrap();
copy_file(&dir.join("big.bin"), &dir.join("copy.bin")).unwrap();
assert!(fs::read(dir.join("copy.bin")).unwrap() == data);
fs::remove_dir_all(&dir).unwrap();
}
#[test]
fn link_at_src() {
let dir = new_dir("link");
fs::write(dir.join("target.txt"), "alpha\n").unwrap();
symlink("target.txt", dir.join("link.txt")).unwrap();
copy_file(&dir.join("link.txt"), &dir.join("b.txt")).unwrap();
assert!(!fs::symlink_metadata(dir.join("b.txt")).unwrap().file_type().is_symlink());
assert_eq!(fs::read_to_string(dir.join("b.txt")).unwrap(), "alpha\n");
fs::remove_dir_all(&dir).unwrap();
}
#!/usr/bin/env bash
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/copy-a-file/.
# copy_file SRC DST
# Copies the bytes and the permission bits of the file at SRC to DST, and
# replaces a file at DST. cp copies into a directory at DST, so the function
# returns status 1 for a directory at SRC or DST. It also returns status 1
# when SRC and DST name the same file. cp -p gives DST the permission bits of
# SRC also when DST exists; with no -p, cp keeps the bits of the old DST. -p
# also copies the times. -- stops options, so a name that starts with - is a
# file name.
copy_file() {
if [[ -d $1 ]]; then
printf 'copy_file: %s: is a directory\n' "$1" >&2
return 1
fi
if [[ -d $2 ]]; then
printf 'copy_file: %s: is a directory\n' "$2" >&2
return 1
fi
if [[ -e $2 && $1 -ef $2 ]]; then
printf 'copy_file: %s and %s are the same file\n' "$1" "$2" >&2
return 1
fi
cp -p -- "$1" "$2" </dev/null
}
test_copy_file.bats 105 lines
#!/usr/bin/env bats
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/copy-a-file/.
bats_require_minimum_version 1.5.0
setup() {
source "$BATS_TEST_DIRNAME/copy_file.sh"
dir=$BATS_TEST_TMPDIR
}
@test "copy" {
printf 'alpha\n' >"$dir/a.txt"
copy_file "$dir/a.txt" "$dir/b.txt"
[ "$(cat "$dir/b.txt")" = alpha ]
[ "$(cat "$dir/a.txt")" = alpha ]
}
@test "replace existing" {
printf 'alpha\n' >"$dir/a.txt"
printf 'beta, a longer text\n' >"$dir/b.txt"
copy_file "$dir/a.txt" "$dir/b.txt"
cmp "$dir/a.txt" "$dir/b.txt"
}
@test "empty file" {
: >"$dir/a.txt"
printf 'beta\n' >"$dir/b.txt"
copy_file "$dir/a.txt" "$dir/b.txt"
[ ! -s "$dir/b.txt" ]
}
@test "other directory" {
mkdir "$dir/sub"
printf 'alpha\n' >"$dir/a.txt"
copy_file "$dir/a.txt" "$dir/sub/a.txt"
[ "$(cat "$dir/sub/a.txt")" = alpha ]
}
@test "name with spaces" {
printf 'alpha\n' >"$dir/my notes.txt"
copy_file "$dir/my notes.txt" "$dir/copy of my notes.txt"
[ "$(cat "$dir/copy of my notes.txt")" = alpha ]
}
@test "non-ascii name" {
printf 'alpha\n' >"$dir/a.txt"
copy_file "$dir/a.txt" "$dir/café 日本.txt"
[ "$(cat "$dir/café 日本.txt")" = alpha ]
}
@test "binary data" {
printf '\0\r\n\303\277\0' >"$dir/a.bin"
copy_file "$dir/a.bin" "$dir/b.bin"
cmp "$dir/a.bin" "$dir/b.bin"
[ "$(wc -c <"$dir/b.bin" | tr -d ' ')" = 6 ]
}
@test "missing src or dst directory" {
run -1 copy_file "$dir/a.txt" "$dir/b.txt"
printf 'alpha\n' >"$dir/a.txt"
run -1 copy_file "$dir/a.txt" "$dir/no-such-dir/b.txt"
}
@test "directory at src or dst" {
mkdir "$dir/dir"
printf 'alpha\n' >"$dir/a.txt"
run -1 copy_file "$dir/dir" "$dir/b.txt"
run -1 copy_file "$dir/a.txt" "$dir/dir"
[ -z "$(ls -A "$dir/dir")" ]
[ ! -e "$dir/b.txt" ]
}
@test "same file" {
printf 'alpha\n' >"$dir/a.txt"
ln "$dir/a.txt" "$dir/b.txt"
run -1 copy_file "$dir/a.txt" "$dir/a.txt"
run -1 copy_file "$dir/a.txt" "$dir/b.txt"
[ "$(cat "$dir/a.txt")" = alpha ]
}
@test "permission bits" {
printf 'echo alpha\n' >"$dir/a.sh"
printf 'beta\n' >"$dir/c.sh"
chmod 750 "$dir/a.sh"
chmod 640 "$dir/c.sh"
copy_file "$dir/a.sh" "$dir/b.sh"
copy_file "$dir/a.sh" "$dir/c.sh"
[[ $(ls -l "$dir/b.sh") == -rwxr-x---* ]]
[[ $(ls -l "$dir/c.sh") == -rwxr-x---* ]]
}
@test "large file" {
head -c 5000003 /dev/urandom >"$dir/big.bin"
copy_file "$dir/big.bin" "$dir/copy.bin"
cmp "$dir/big.bin" "$dir/copy.bin"
}
@test "link at src" {
printf 'alpha\n' >"$dir/target.txt"
ln -s target.txt "$dir/link.txt"
copy_file "$dir/link.txt" "$dir/b.txt"
[ ! -L "$dir/b.txt" ]
[ "$(cat "$dir/b.txt")" = alpha ]
}
References
- The Python Standard Library, shutil, High-level file operations, shutil.copyfile, shutil.copy, shutil.copy2, Platform-dependent efficient copy operations
- Node.js documentation, File system, fsPromises.copyFile(src, dest[, mode])
- Java SE 25 API, Files, copy(Path, Path, CopyOption...), StandardCopyOption
- .NET API reference, File.Copy Method, Copy(String, String, Boolean), Remarks
- Go standard library, package os, func SameFile, func CopyFS
- Go standard library, package io, func Copy
- The Rust Standard Library, std::fs::copy, Description, Platform-specific behavior
- The Open Group Base Specifications Issue 8 (POSIX.1-2024), cp, DESCRIPTION, OPTIONS (-p)
- Linux manual page, copy_file_range(2), DESCRIPTION
- Linux manual page, ioctl_ficlone(2), DESCRIPTION
- cppreference, std::filesystem::copy_file, Description
- Windows API reference, CopyFileExW function (winbase.h), Syntax
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Code (bash) | I0 not checked yet |
|
| Code (c) | I0 not checked yet |
|
| Code (cpp) | I0 not checked yet |
|
| Code (csharp) | I0 not checked yet |
|
| Code (go) | I0 not checked yet |
|
| Code (java) | I0 not checked yet |
|
| Code (javascript) | I0 not checked yet |
|
| Code (python) | I0 not checked yet |
|
| Code (rust) | I0 not checked yet |
|
| Code (typescript) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W3 standard |
|
Tag 7DWYBX Edit this page History Report an error Markdown