C++ FileIO Copy -VS-系统("cp file1.x file2.x)

Mic*_*ICE 12 c++ linux filesystems g++

编写文件复制例程是否更快/更高效,还是应该只执行对cp的系统调用?

(文件系统可能有所不同[nfs,local,reiser等],但它总是在CentOS linux系统上)

小智 22

调用一个通过使用系统()函数的效率不高,而不是非常安全的.

在Linux中复制文件的最有效方法是使用sendfile()系统调用.在Windows上,应使用CopyFile() API函数或其相关变体之一.

使用sendfile的示例:

#include <fcntl.h>
#include <stdlib.h>
#include <stdio.h>
#include <sys/sendfile.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>

int main (int argc, char* argv[])
{
 int read_fd;
 int write_fd;
 struct stat stat_buf;
 off_t offset = 0;

 /* Open the input file. */
 read_fd = open (argv[1], O_RDONLY);
 /* Stat the input file to obtain its size. */
 fstat (read_fd, &stat_buf);
 /* Open the output file for writing, with the same permissions as the
   source file. */
 write_fd = open (argv[2], O_WRONLY | O_CREAT, stat_buf.st_mode);
 /* Blast the bytes from one file to the other. */
 sendfile (write_fd, read_fd, &offset, stat_buf.st_size);
 /* Close up. */
 close (read_fd);
 close (write_fd);

 return 0;
}
Run Code Online (Sandbox Code Playgroud)

如果您不希望您的代码依赖于平台,您可能会使用更便携的解决方案 - Boost File System库std :: fstream.

使用Boost的示例(更完整的示例):

copy_file (source_path, destination_path, copy_option::overwrite_if_exists);
Run Code Online (Sandbox Code Playgroud)

使用C++ std :: fstream的示例:

ifstream f1 ("input.txt", fstream::binary);
ofstream f2 ("output.txt", fstream::trunc|fstream::binary);
f2 << f1.rdbuf ();
Run Code Online (Sandbox Code Playgroud)