文件零拷贝实现文件拷贝到其他目录
#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 是目标文件的路径。如果一切正常,该命令将会将源文件的内容复制到目标文件中,实现文件的复制操作。