从 istream 到 ostream 的快速受控复制 [英] Fast controlled copy from istream to ostream
问题描述
我必须将几个字节从 istream
复制到 ostream
,我知道有两种方法可以执行此复制.
I have to copy several bytes from a istream
to a ostream
, there are 2 ways that I know to perform this copy.
myostream << myistream.rdbuf();
和
copy( istreambuf_iterator<char>(myistream),
istreambuf_iterator<char>(),
ostreambuf_iterator<char>(myostream)
);
我发现 rdbuf
版本的速度至少是 copy
版本的两倍.
我还没有找到仅复制 100 字节的方法,但由于要复制的大小可能会很大,我希望能够使用 rdbuf
版本(如果可能).
I've found that rdbuf
version is at least twice as fast as the copy
.
I haven't found yet the way of copying just, say 100 bytes, but as the size to be copied will probably be quite big I would like to be able to use the rdbuf
version if posible.
如何将这些副本限制为给定的字节数?
How to limit those copies to a given number of bytes?
推荐答案
你能用 0x 吗?如果是这样,那么您可以使用 copy_n:
Can you use 0x? If so, then you can use copy_n:
copy_n( istreambuf_iterator<char>(myistream),
100,
ostreambuf_iterator<char>(myostream)
);
编辑 1:
我知道您可能正在寻找一个库解决方案,并且您可能已经自己解决了这个问题.但如果你没有想到这样的事情,这就是我会做的(如果我没有 copy_n):
I know you're probably looking for a library solution, and you could probably have figured this out on your own. But in case you haven't thought of something like this, here's what I would do(if I didn't have copy_n):
void stream_copy_n(std::istream & in, std::size_t count, std::ostream & out)
{
const std::size_t buffer_size = 4096;
char buffer[buffer_size];
while(count > buffer_size)
{
in.read(buffer, buffer_size);
out.write(buffer, buffer_size);
count -= buffer_size;
}
in.read(buffer, count);
out.write(buffer, count);
}
这篇关于从 istream 到 ostream 的快速受控复制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!