复制部分文件的C++/增强方式



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

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

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

我认为最有效的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);
}

根据注释,根据操作系统的不同,您的里程可能会因系统调用(如 splice 和 sendfile(而异,但请注意手册页中的注释:

应用程序可能希望在 sendfile(( 因 EINVAL 或 ENOSYS 失败的情况下回退到 read(2(/write(2(。

如果没有,那么我似乎需要使用 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;
}

异常处理待办事项。

最新更新