复制部分文件的C ++ / boost方法

时间:2018-09-25 11:18:52

标签: c++ boost

我知道有boost:filesystem::copy_file可以复制整个文件。 但是我需要从一开始就将文件的一部分复制到其他文件的特定偏移量。我的问题是是否有任何动力可以做到这一点?

否则,似乎我需要使用fopen/fread/fwrite并实现自己的自定义复制循环。

更新:我不要求复制文件的最有效方法。我没有提到Linux。我不知道如何将这个问题视为“在Linux上复制文件的最有效方法”问题的重复。看起来所有将其标记为重复的人根本没有读过我的问题。

2 个答案:

答案 0 :(得分:1)

我认为最有效的boost路由是源文件的内存映射文件和目标文件的直接写入。

该程序带有2个文件名参数。它将源文件的前一半复制到目标文件。

#include <boost/iostreams/device/mapped_file.hpp>
#include <iostream>
#include <fstream>
#include <cstdio>

namespace iostreams = boost::iostreams;
int main(int argc, char** argv)
{
    if (argc != 3)
    {
        std::cerr << "usage: " << argv[0] << " <infile> <outfile> - 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);
}

根据注释,视操作系统而定,您的里程可能随系统调用(例如splicesendfile)的不同而变化,但是请注意手册页中的注释:

  

如果sendfile()因EINVAL或ENOSYS失败,应用程序可能希望退回到read(2)/ write(2)。

答案 1 :(得分:1)

  

否则,似乎我需要使用fopen / fread / fwrite并实现自己的自定义复制循环。

只是为了说明Boost和C之间存在一种香草解决方案。

#include <fstream>
#include <algorithm>
#include <iterator>

int main()
{
    std::ifstream fin("in",std::ios_base::binary);
    fin.exceptions(std::ios::failbit | std::ios::badbit);
    std::ofstream fout("out",std::ios_base::binary);
    fout.exceptions(std::ios::failbit | std::ios::badbit);
    std::istream_iterator<char> iit(fin);
    std::ostream_iterator<char> oit(fout);
    std::copy_n(iit,42,oit);
    return 0;
}

异常处理TODO。