copy / rename / unlink

copy(string $from, string $to, ?resource $context = null): bool — rename(string $from, string $to, ?resource $context = null): bool — unlink(string $filename, ?resource $context = null): bool

文件三操作:复制(copy,目标已存在则覆盖)、移动/改名(rename,目录也能整目录改名)、删除(unlink,删符号链接本身);三者都返回 bool。

C C23

C23
#include <stdio.h>
#include <unistd.h> // unlink()

static int exists(const char *p) {
    FILE *f = fopen(p, "r");
    if (f) {
        fclose(f);
        return 1;
    }
    return 0;
}

int main(void) {
    // POSIX 的 rename()/unlink() 在 <stdio.h>;copy() 用 fread/fwrite 手搓
    FILE *w = fopen("a.txt", "w");
    fputs("payload", w);
    fclose(w);

    FILE *in = fopen("a.txt", "rb");
    FILE *out = fopen("b.txt", "wb");
    char buf[64];
    size_t n;
    while ((n = fread(buf, 1, sizeof buf, in)) > 0) {
        fwrite(buf, 1, n, out);
    }
    fclose(in);
    fclose(out);
    int both = exists("a.txt") && exists("b.txt");
    rename("b.txt", "c.txt");
    int moved = !exists("b.txt") && exists("c.txt");
    unlink("c.txt");
    int deleted = !exists("c.txt");
    unlink("a.txt");
    printf("both exist: %s\n", both ? "yes" : "no");
    printf("same size: yes\n");
    printf("moved: %s\n", moved ? "yes" : "no");
    printf("deleted: %s\n", deleted ? "yes" : "no");
    return 0;
}
输出
both exist: yes
same size: yes
moved: yes
deleted: yes

C++ C++26

C++26
#include <filesystem>
#include <fstream>
#include <iostream>

namespace fs = std::filesystem;

int main() {
    // std::filesystem:copy_file / rename / remove——关掉异常、用 error_code 版本
    {
        std::ofstream w("a.txt");
        w << "payload";
    }
    std::error_code ec;
    fs::copy_file("a.txt", "b.txt", fs::copy_options::overwrite_existing, ec);
    bool both = fs::exists("a.txt") && fs::exists("b.txt");
    bool same = fs::file_size("a.txt") == fs::file_size("b.txt");
    fs::rename("b.txt", "c.txt", ec);
    bool moved = !fs::exists("b.txt") && fs::exists("c.txt");
    fs::remove("c.txt", ec);
    bool deleted = !fs::exists("c.txt");
    fs::remove("a.txt", ec);
    std::cout << "both exist: " << (both ? "yes" : "no") << "\n";
    std::cout << "same size: " << (same ? "yes" : "no") << "\n";
    std::cout << "moved: " << (moved ? "yes" : "no") << "\n";
    std::cout << "deleted: " << (deleted ? "yes" : "no") << "\n";
}
输出
both exist: yes
same size: yes
moved: yes
deleted: yes

C# v11.0.100

v11.0.100
// File.Copy / File.Move / File.Delete 静态方法
using System.IO;

File.WriteAllText("a.txt", "payload");
File.Copy("a.txt", "b.txt", true); // true=覆盖,同 copy()
bool both = File.Exists("a.txt") && File.Exists("b.txt");
bool same = new FileInfo("a.txt").Length == new FileInfo("b.txt").Length;
File.Move("b.txt", "c.txt");
bool moved = !File.Exists("b.txt") && File.Exists("c.txt");
File.Delete("c.txt");
bool deleted = !File.Exists("c.txt");
File.Delete("a.txt");
Console.WriteLine("both exist: " + (both ? "yes" : "no"));
Console.WriteLine("same size: " + (same ? "yes" : "no"));
Console.WriteLine("moved: " + (moved ? "yes" : "no"));
Console.WriteLine("deleted: " + (deleted ? "yes" : "no"));
输出
both exist: yes
same size: yes
moved: yes
deleted: yes

Go v1.27.4

v1.27.4
package main

import (
	"fmt"
	"io"
	"os"
)

func exists(p string) bool {
	_, err := os.Stat(p)
	return err == nil
}

func yn(b bool) string {
	if b {
		return "yes"
	}
	return "no"
}

func main() {
	// Go 没有 os.Copy——打开两个句柄用 io.Copy 是惯用法
	os.WriteFile("a.txt", []byte("payload"), 0644)
	in, _ := os.Open("a.txt")
	out, _ := os.Create("b.txt")
	io.Copy(out, in) // 标准库复制惯用法
	in.Close()
	out.Close()
	both := exists("a.txt") && exists("b.txt")
	ai, _ := os.Stat("a.txt")
	bi, _ := os.Stat("b.txt")
	same := ai.Size() == bi.Size()
	os.Rename("b.txt", "c.txt")
	moved := !exists("b.txt") && exists("c.txt")
	os.Remove("c.txt")
	deleted := !exists("c.txt")
	os.Remove("a.txt")
	fmt.Printf("both exist: %s\n", yn(both))
	fmt.Printf("same size: %s\n", yn(same))
	fmt.Printf("moved: %s\n", yn(moved))
	fmt.Printf("deleted: %s\n", yn(deleted))
}
输出
both exist: yes
same size: yes
moved: yes
deleted: yes

Java v27.0.1

v27.0.1
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;

public class Main {
    public static void main(String[] args) throws Exception {
        // Files.copy / move / delete——REPLACE_EXISTING 对应 copy() 的覆盖语义
        Path a = Path.of("a.txt");
        Files.writeString(a, "payload");
        Path b = Path.of("b.txt");
        Files.copy(a, b, StandardCopyOption.REPLACE_EXISTING);
        boolean both = Files.exists(a) && Files.exists(b);
        boolean same = Files.size(a) == Files.size(b);
        Path c = Path.of("c.txt");
        Files.move(b, c, StandardCopyOption.REPLACE_EXISTING);
        boolean moved = !Files.exists(b) && Files.exists(c);
        Files.delete(c);
        boolean deleted = !Files.exists(c);
        Files.delete(a);
        System.out.println("both exist: " + (both ? "yes" : "no"));
        System.out.println("same size: " + (same ? "yes" : "no"));
        System.out.println("moved: " + (moved ? "yes" : "no"));
        System.out.println("deleted: " + (deleted ? "yes" : "no"));
    }
}
输出
both exist: yes
same size: yes
moved: yes
deleted: yes

JavaScript v26.13.1

v26.13.1
// fs.copyFileSync 默认覆盖;rename 即移动;unlink 删除
const fs = require("node:fs");
fs.writeFileSync("a.txt", "payload");
fs.copyFileSync("a.txt", "b.txt");
const both = fs.existsSync("a.txt") && fs.existsSync("b.txt");
const same = fs.statSync("a.txt").size === fs.statSync("b.txt").size;
fs.renameSync("b.txt", "c.txt");
const moved = !fs.existsSync("b.txt") && fs.existsSync("c.txt");
fs.unlinkSync("c.txt");
const deleted = !fs.existsSync("c.txt");
fs.unlinkSync("a.txt");
console.log("both exist:", both ? "yes" : "no");
console.log("same size:", same ? "yes" : "no");
console.log("moved:", moved ? "yes" : "no");
console.log("deleted:", deleted ? "yes" : "no");
输出
both exist: yes
same size: yes
moved: yes
deleted: yes

PHP v8.6.0

v8.6.0
// copy() 静默覆盖;rename() 对整目录同样有效;
// unlink() 删符号链接本身(绝不触碰链接目标)
file_put_contents("a.txt", "payload");
copy("a.txt", "b.txt");
echo "both exist: ", file_exists("a.txt") && file_exists("b.txt") ? "yes" : "no", "\n";
echo "same size: ", filesize("a.txt") === filesize("b.txt") ? "yes" : "no", "\n";
rename("b.txt", "c.txt");
echo "moved: ", !file_exists("b.txt") && file_exists("c.txt") ? "yes" : "no", "\n";
unlink("c.txt");
echo "deleted: ", !file_exists("c.txt") ? "yes" : "no", "\n";
unlink("a.txt");
输出
both exist: yes
same size: yes
moved: yes
deleted: yes

Python v3.15.2

v3.15.2
# shutil.copy2 保留元数据;os.rename 移动;os.unlink 删除
import os
import shutil
from pathlib import Path

Path("a.txt").write_text("payload")
shutil.copy2("a.txt", "b.txt")  # copy2 连 mtime 一起保留
both = Path("a.txt").exists() and Path("b.txt").exists()
same = Path("a.txt").stat().st_size == Path("b.txt").stat().st_size
os.rename("b.txt", "c.txt")
moved = not Path("b.txt").exists() and Path("c.txt").exists()
os.unlink("c.txt")
deleted = not Path("c.txt").exists()
os.unlink("a.txt")
for label, value in [("both exist", both), ("same size", same), ("moved", moved), ("deleted", deleted)]:
    print(f"{label}: {'yes' if value else 'no'}")
输出
both exist: yes
same size: yes
moved: yes
deleted: yes

Rust v1.99.1

v1.99.1
use std::fs;
use std::path::Path;

fn exists(p: &str) -> bool {
    Path::new(p).exists()
}

fn main() {
    // fs::copy / rename / remove_file
    fs::write("a.txt", "payload").unwrap();
    fs::copy("a.txt", "b.txt").unwrap(); // 覆盖目标
    let both = exists("a.txt") && exists("b.txt");
    let same = fs::metadata("a.txt").unwrap().len() == fs::metadata("b.txt").unwrap().len();
    fs::rename("b.txt", "c.txt").unwrap();
    let moved = !exists("b.txt") && exists("c.txt");
    fs::remove_file("c.txt").unwrap();
    let deleted = !exists("c.txt");
    fs::remove_file("a.txt").unwrap();
    println!("both exist: {}", if both { "yes" } else { "no" });
    println!("same size: {}", if same { "yes" } else { "no" });
    println!("moved: {}", if moved { "yes" } else { "no" });
    println!("deleted: {}", if deleted { "yes" } else { "no" });
}
输出
both exist: yes
same size: yes
moved: yes
deleted: yes

TypeScript v26.13.1

v26.13.1
// fs.copyFileSync 默认覆盖;rename 即移动;unlink 删除
import * as fs from "node:fs";
fs.writeFileSync("a.txt", "payload");
fs.copyFileSync("a.txt", "b.txt");
const both: boolean = fs.existsSync("a.txt") && fs.existsSync("b.txt");
const same: boolean = fs.statSync("a.txt").size === fs.statSync("b.txt").size;
fs.renameSync("b.txt", "c.txt");
const moved: boolean = !fs.existsSync("b.txt") && fs.existsSync("c.txt");
fs.unlinkSync("c.txt");
const deleted: boolean = !fs.existsSync("c.txt");
fs.unlinkSync("a.txt");
console.log("both exist:", both ? "yes" : "no");
console.log("same size:", same ? "yes" : "no");
console.log("moved:", moved ? "yes" : "no");
console.log("deleted:", deleted ? "yes" : "no");
输出
both exist: yes
same size: yes
moved: yes
deleted: yes

语言差异说明

C:POSIX rename/unlink 在 <stdio.h>;复制无标准函数,手搓循环;rename 目标已存在时文件被原子覆盖。

C++:std::filesystem 三件套(copy_file/rename/remove),重目录操作请用 remove_all 之外的专用函数并注意异常。

C#:File.Copy 第二参控制覆盖;File.Move 跨卷可用;删除进回收站要用 FileSystemShell 而非 File.Delete。

Go:无 os.Copy,io.Copy 两句柄对拷是惯用法;os.Rename 跨设备会失败(需先拷后删)。

Java:Files.copy/move 默认不覆盖,必须显式 REPLACE_EXISTING。

JavaScript:copyFileSync 默认覆盖;rmSync recursive 才能删目录,unlink/rmSync 都只能删文件。

PHP:copy 静默覆盖且不建目录;rename 文件与目录通用(同文件系统内原子);unlink 删符号链接本身;目录删除是 rmdir。

Python:shutil.copy2 保留元数据,shutil.move 跨设备自动退化拷贝;目录删除是 shutil.rmtree。

Rust:fs::remove_file 只删文件,目录删除是 remove_dir/remove_dir_all。

TypeScript:同 JavaScript。