Would it be quicker/efficient to write a file copy routine or should I just execute a System call to cp?
(The file system could differ [nfs, local, reiser, etc], however
Invoking a shell by using system () function is not efficient and not very secure.
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.
Example using 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;
}
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.
Example using Boost (more complete example):
copy_file (source_path, destination_path, copy_option::overwrite_if_exists);
Example using C++ std::fstream:
ifstream f1 ("input.txt", fstream::binary);
ofstream f2 ("output.txt", fstream::trunc|fstream::binary);
f2 << f1.rdbuf ();
With your own routine you can control the size of the block used for copying, which you can't do with cp. Also, you can spawn different threads for reading and writing data (to further speed up process). Finally, spawning an external process takes extra time (important if you copy small files).
I would put my money on that the OS knows the most efficient way to copy file A to file B. The same applies for any api functions.
C++ File IO is more portable and more low-level, so it is more flexible.
It would not be time efficient to write a file copy routine.
It is resource intensive to call system to shell a cp.
You'll be far better served by figuring out the system (function) call that you can make to copy the file. E.g. on Windows it's just CopyFile(src, dst)
if I recall correctly.