[英]Copy only part of a binary file in C++
This is a nice and intuitive way to copy files:这是复制文件的一种很好且直观的方式:
#include <fstream>
int main()
{
std::ifstream src("from.bn", std::ios::binary);
std::ofstream dst("to.bn", std::ios::binary);
dst << src.rdbuf();
}
How can one modify it in order to just copy the first n bytes of src
?如何修改它以便只复制
src
的前n个字节?
For the first n characters , you can use:对于前n 个字符,您可以使用:
std::copy_n(std::istreambuf_iterator<char>(src), n, std::ostreambuf_iterator<char>(dst));
If you're not sure that their will be 'enough' data in the input stream, you can use readsome()
to get what's there, up to a given limit (if you know there will be a big enough input stream, just use read
):如果您不确定输入 stream 中的数据是否“足够”,您可以使用
readsome()
来获取其中的内容,直到给定限制(如果您知道输入 stream 将有足够大的数据,只需使用read
):
#include <fstream>
int main()
{
constexpr size_t amount = 4242;
char data[amount];
std::ifstream src("from.bn", std::ios::binary);
std::ofstream dst("to.bn", std::ios::binary);
size_t actual = src.readsome(data, amount);
dst.write(data, actual);
return 0;
}
You can use the .read()
method of std::ifstream, which enables you to read N bytes of data.您可以使用 std::ifstream 的
.read()
方法,该方法使您能够读取 N 个字节的数据。
To be fully changeable, you can add a call to .seekg()
, to move into the file.要完全更改,您可以添加对
.seekg()
的调用以移入文件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.