Invoking un shell utilizzando la funzione system() non è efficiente e non molto sicuro.
Il modo più efficace per copiare un file in Linux è quello di utilizzare sendfile() chiamata di sistema. Su Windows, CopyFile() È necessario utilizzare la funzione API o una delle sue varianti correlate.
Example utilizzando 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;
}
Se non si desidera che il codice sia dipendente dalla piattaforma, si può attaccare con più soluzioni portatili - Boost File System library o std::fstream.
Esempio con Boost (more complete example):
copy_file (source_path, destination_path, copy_option::overwrite_if_exists);
Esempio in C++ std::fstream:
ifstream f1 ("input.txt", fstream::binary);
ofstream f2 ("output.txt", fstream::trunc|fstream::binary);
f2 << f1.rdbuf();
fonte
2010-09-09 21:47:49
possibile duplicato di [copiare un file in un modo sano, sicuro ed efficiente] (http: // stackoverflow.com/questions/10195343/copy-a-file-in-an-sane-safe-and-efficient-way) –