Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
809 views
in Technique[技术] by (71.8m points)

c++ - Fast controlled copy from istream to 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();

and

copy( istreambuf_iterator<char>(myistream),
      istreambuf_iterator<char>(),
      ostreambuf_iterator<char>(myostream)
);

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Can you use 0x? If so, then you can use copy_n:

copy_n( istreambuf_iterator<char>(myistream),
        100,
        ostreambuf_iterator<char>(myostream)
);

EDIT 1:

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);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...