c++ - C++/boost复制部分文件的方法
问题描述
我知道有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)。
推荐阅读
- scrapy - 当我得到base64时如何用scrapy下载图像
- c# - 创建正则表达式以匹配带有字母后跟固定位数的字符串
- css - 如何解决有关外部样式表链接的问题,该链接不在编程文件的同一目录中,但可以工作?
- angular - 在 (click) angular 5 中包含两个函数
- r - ggplot 中的颜色,提供给离散比例的连续值
- python - 如何在 Spark RDD 中比较不区分大小写的字符串?
- http - 使用 ipv6 的邮递员 GET 请求
- python - TensorFlow:可训练标志 - tf.nn.conv2d vs tf.layers.conv2d
- php - 如何在不使用 php oracle 循环的情况下仅获取 1 行
- javascript - 如何使用 Object.assign() 函数复制/覆盖对象?