首页 > 解决方案 > C++/boost复制部分文件的方法

问题描述

我知道有boost:filesystem::copy_file允许复制整个文件。但我需要将文件的一部分从开头复制到其他文件的某个特定偏移量。我的问题是,是否有任何促进措施可以做到这一点?

如果没有,那么我似乎需要使用fopen/fread/fwrite和实现我自己的自定义复制循环。

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

标签: c++boost

解决方案


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)。


推荐阅读