- 论坛徽章:
- 17
|
回复 1# Herowinter
如果有系统调用最好还是用系统调用,自己写代码实现的文件copy需要在程序在用户态和内核态频繁的切换,文件大了这个开销是很可观的。可以参数下面的代码:- #include <fcntl.h>
- #include <unistd.h>
- #if defined(__APPLE__) || defined(__FreeBSD__)
- #include <copyfile.h>
- #else
- #include <sys/sendfile.h>
- #endif
- int OSCopyFile(const char* source, const char* destination)
- {
- int input, output;
- if ((input = open(source, O_RDONLY)) == -1)
- {
- return -1;
- }
- if ((output = open(destination, O_RDWR | O_CREAT)) == -1)
- {
- close(input);
- return -1;
- }
- //Here we use kernel-space copying for performance reasons
- #if defined(__APPLE__) || defined(__FreeBSD__)
- //fcopyfile works on FreeBSD and OS X 10.5+
- int result = fcopyfile(input, output, 0, COPYFILE_ALL);
- #else
- //sendfile will work with non-socket output (i.e. regular file) on Linux 2.6.33+
- off_t bytesCopied = 0;
- struct stat fileinfo = {0};
- fstat(input, &fileinfo);
- int result = sendfile(output, input, &bytesCopied, fileinfo.st_size);
- #endif
- close(input);
- close(output);
- return result;
- }
复制代码 引用自:http://stackoverflow.com/questio ... ile-on-unix-using-c |
|