Stream Buffers
The I/O stream classes rely on stream buffers for the low-level input and output. Most programmers ignore the stream buffer and deal only with high-level streams. You might find yourself dealing with stream buffers from the client side—for example, using stream buffers to perform low-level I/O on entire streams at once—or you might find yourself on the other side, implementing a custom stream buffer. This section discusses both of these aspects.
You can copy a file in several ways. Example 9-3 shows how a C programmer might copy a stream once he has learned about templates.
template<typename charT, typename traits> void copy(std::basic_ostream<charT, traits>& out, std::basic_istream<charT, traits>& in) { charT c; while (in.get(c)) out.put(c); }
After measuring the performance of this solution, the intrepid programmer might decide that copying larger buffers is the right way to go. Example 9-4 shows the new approach. On my system, the new version runs roughly twice as fast as the original version. (Of course, performance measures depend highly on compiler, library, environment, and so on.)
template<typename charT, typename traits> void copy(std::basic_ostream<charT, traits>& out, std::basic_istream<charT, traits>& in) { const unsigned BUFFER_SIZE = 8192; std::auto_ptr<charT> buffer(new charT[BUFFER_SIZE]); while (in) { in.read(buffer.get( ), BUFFER_SIZE); out.write(buffer.get( ...
Get C++ In a Nutshell now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.