Most efficient way to copy a file in Linux

后端 未结 5 432
故里飘歌
故里飘歌 2020-12-07 11:51

I am working at an OS independent file manager, and I am looking at the most efficient way to copy a file for Linux. Windows has a built in function, CopyFileEx(), but from

5条回答
  •  遥遥无期
    2020-12-07 12:16

    My answer from a more recent duplicate of this post.

    boost now offers mapped_file_source which portably models a memory-mapped file.

    Maybe not as efficient as CopyFileEx() and splice(), but portable and succinct.

    This program takes 2 filename arguments. It copies the first half of the source file to the destination file.

    #include 
    #include 
    #include 
    #include 
    
    namespace iostreams = boost::iostreams;
    int main(int argc, char** argv)
    {
        if (argc != 3)
        {
            std::cerr << "usage: " << argv[0] << "   - copies half of the infile to outfile" << std::endl;
            std::exit(100);
        }
    
        auto source = iostreams::mapped_file_source(argv[1]);
        auto dest = std::ofstream(argv[2], std::ios::binary);
        dest.exceptions(std::ios::failbit | std::ios::badbit);
        auto first = source. begin();
        auto bytes = source.size() / 2;
        dest.write(first, bytes);
    }
    

    Depending on OS, your mileage may vary with system calls such as splice and sendfile, however note the comments in the man page:

    Applications may wish to fall back to read(2)/write(2) in the case where sendfile() fails with EINVAL or ENOSYS.

提交回复
热议问题