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

前端 未结 5 1907
自闭症患者
自闭症患者 2021-01-31 22:15

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

5条回答
  •  心在旅途
    2021-01-31 22:53

    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 
    #include 
    #include 
    #include 
    #include 
    #include 
    #include 
    
    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 ();
    

提交回复
热议问题