零拷贝文件到其他目录

文件零拷贝实现文件拷贝到其他目录

#include <iostream>
#include <fcntl.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/sendfile.h>

int main(int argc, char* argv[]) {
    if (argc != 3) {
        std::cerr << "Usage: " << argv[0] << " <source_file> <dest_file>\n";
        return -1;
    }

    // 打开源文件
    int src_fd = open(argv[1], O_RDONLY);
    if (src_fd == -1) {
        perror("open");
        return -1;
    }

    // 创建目标文件
    int dest_fd = open(argv[2], O_RDWR | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
    if (dest_fd == -1) {
        perror("open");
        close(src_fd);
        return -1;
    }

    // 获取源文件大小
    struct stat st;
    if (fstat(src_fd, &st) == -1) {
        perror("fstat");
        close(dest_fd);
        close(src_fd);
        return -1;
    }

    // 使用 sendfile 函数实现零拷贝
    off_t offset = 0;
    ssize_t ret = sendfile(dest_fd, src_fd, &offset, st.st_size);
    if (ret == -1) {
        perror("sendfile");
        close(dest_fd);
        close(src_fd);
        return -1;
    }

    // 关闭文件
    close(src_fd);
    close(dest_fd);

    return 0;
}

可以在终端命令行中编译并运行这段 C++ 代码,例如:

g++ file_copy.cpp -o file_copy
./file_copy /path/to/source_file /path/to/destination_file

其中,file_copy.cpp 是上述 C++ 代码所在的文件,/path/to/source_file 是源文件的路径,/path/to/destination_file 是目标文件的路径。如果一切正常,该命令将会将源文件的内容复制到目标文件中,实现文件的复制操作。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值