C ++ FileIO复制-VS-系统(“cp file1.x file2.x) [英] C++ FileIO Copy -VS- System("cp file1.x file2.x)
问题描述
编写文件复制例程会更快/更有效率,还是应该对cp执行系统调用?
Would it be quicker/efficient to write a file copy routine or should I just execute a System call to cp?
(文件系统可能不同[nfs,
(The file system could differ [nfs, local, reiser, etc], however it would always be on a CentOS linux system)
推荐答案
通过使用启用 外壳 > system() 功能效率不高且不是很安全。
Invoking a shell by using system () function is not efficient and not very secure.
在Linux中复制文件的最有效的方法是使用 sendfile() 系统调用。
在Windows上, CopyFile() API函数或其相关变体之一。
The most efficient way to copy a file in Linux is to use sendfile () system call. On Windows, CopyFile () API function or one of its related variants should be used.
#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;
}
如果您不希望代码与平台相关,更便携的解决方案 - Boost文件系统库或 std :: fstream 。
If you do not want your code to be platform dependent, you may stick with more portable solutions - Boost File System library or std::fstream.
使用Boost的示例href =http://www.boost.org/doc/libs/1_44_0/libs/filesystem/v2/test/operations_test.cpp>更完整的示例):
Example using Boost (more complete example):
copy_file (source_path, destination_path, copy_option::overwrite_if_exists);
ifstream f1 ("input.txt", fstream::binary);
ofstream f2 ("output.txt", fstream::trunc|fstream::binary);
f2 << f1.rdbuf ();
这篇关于C ++ FileIO复制-VS-系统(“cp file1.x file2.x)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!