Note that there are some explanatory texts on larger screens.

plurals
  1. POCopying one std stream to another efficiently
    text
    copied!<p>Ok, Here's some code that outlines what I'm trying to do.</p> <pre><code>#include &lt;sys/types.h&gt; #include &lt;sys/stat.h&gt; #include &lt;sys/fcntl.h&gt; #include &lt;iostream&gt; #include &lt;sstream&gt; int main( int c, char *v[] ) { int fd = open( "data.out", O_RDONLY | O_NONBLOCK ); std::cout &lt;&lt; "fd = " &lt;&lt; fd &lt;&lt; std::endl; char buffer[ 1024000 ]; ssize_t nread; std::stringstream ss; while( true ) { if ( (nread = read( fd, buffer, sizeof( buffer ) - 1 )) &lt; 0 ) break; ss.write( buffer, nread ); while( true ) { std::stringstream s2; std::cout &lt;&lt; "pre-get : " &lt;&lt; (((ss.rdstate() &amp; std::ios::badbit) == std::ios::badbit) ? "bad" : "") &lt;&lt; " " &lt;&lt; (((ss.rdstate() &amp; std::ios::eofbit) == std::ios::eofbit) ? "eof" : "") &lt;&lt; " " &lt;&lt; (((ss.rdstate() &amp; std::ios::failbit) == std::ios::failbit) ? "fail" : "" ) &lt;&lt; " " &lt;&lt; std::endl; ss.get( *s2.rdbuf() ); std::cout &lt;&lt; "post-get : " &lt;&lt; (((ss.rdstate() &amp; std::ios::badbit) == std::ios::badbit) ? "bad" : "") &lt;&lt; " " &lt;&lt; (((ss.rdstate() &amp; std::ios::eofbit) == std::ios::eofbit) ? "eof" : "") &lt;&lt; " " &lt;&lt; (((ss.rdstate() &amp; std::ios::failbit) == std::ios::failbit) ? "fail" : "" ) &lt;&lt; " " &lt;&lt; std::endl; unsigned int linelen = ss.gcount() - 1; if ( ss.eof() ) { ss.str( s2.str() ); break; } else if ( ss.fail() ) { ss.str( "" ); break; } else { std::cout &lt;&lt; s2.str() &lt;&lt; std::endl; } } } } </code></pre> <p>It firstly reads large chunks of data into a data buffer. I know there's better C++ ways of doing this part but in my real application I am handed a char[] buffer and a length.</p> <p>I then write the buffer into a std::stringstream object so I can remove a line at a time from it.</p> <p>I thought I'd use the get( streambuf &amp; ) method on the stringstream to write one line to another stringstream where I can then output it.</p> <p>Ignoring the fact that this may not be the best way to extract a line at a time from the buffer I've read in (although I'd like anyone to offer up a better alternative to the one I post here), as soon as the first <code>ss.get( *s2.rdbuf() )</code> is called the <code>ss</code> is in a fail state and I can't work out why. There's plenty of data in the input file so <code>ss</code> should definately contain more than one line of input.</p> <p>Any ideas?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload