Re: strstream reinstatement
In article <1157636428.873405.22210@m79g2000cwm.googlegroups.com>,
werasm <w_erasm@telkomsa.net> wrote:
Alberto Ganesh Barbati wrote:
the buffer is local to the function, yet I don't see any trouble as the
lifetime of the buffer clearly outlives the stream object.
... memory based stream buffers....
A lot of the excess copying can be avoid by being less terse,by
using a default constructed stringstream and copying with
an ostreambuf_iterator<char> to the stream and then seeking the
beginning read [seekg(0)] and then reading the stream.
prepending an ostream can be read into a properly sized char array
or vector<char> via std::copy(std::istreambuf_iterator<char>
(stream),...);
std::ostringstream os;
// write to os
foo(os.str().c_str()); // ouch two copies of data
std::stringstream os;
// write to os;
{
std::vector<char> tmp(std::istreambuf_iterator<char>(os),
std::std::istream_iterator<char>()); // one copy of data
tmp.push_back('\0');
foo(&*tmp.begin());
}
initializing a string stream form a '\0' terming terminated char
array does not need to be converted to a string first, since something
like
std::istringstream in("20 10");
// read the stream
can be done with
std::stringstream in;
{
char *p = "20 10";
std::ostreambuf_iterator<char> out(in);
while (*p)
*out++ = *p++;
in.seekg();
}
// read the stream.
note this does no unnecessary conversions to std::string.
seems like the only thing is simple usages that can be handled simple
stream buffers that don't seek, if you don't seek the stream
[seekp,seekp] then the streambuf's defaults [always fail] will work.
so only thing needed is a constructor to set the buffer and end()
function for output only memory buf
struct isimplemembuf:std::streambuf
{
isimplemembuf(char *start,std::ptrdiff_t size)
{setg(start,start,start+size}
char *begin() {return eback();}
char *end() {return egptr();}
};
struct osimplemembuf:std::streambuf
{
osimplemembuf(char *start,std::ptrdiff_t size)
{ setp(start,start+size);}
char *begin() {return pbase();}
char *end() {return pptr();}
};
look simple enough:)
The seekpos and seekoff functions can be written if needed.
Tedious but not complicated...
---
[ comp.std.c++ is moderated. To submit articles, try just posting with ]
[ your news-reader. If that fails, use mailto:std-c++@ncar.ucar.edu ]
[ --- Please see the FAQ before posting. --- ]
[ FAQ: http://www.comeaucomputing.com/csc/faq.html ]