From: Lance Diduck on
On Feb 22, 1:21 am, Rem <therealr...(a)gmail.com> wrote:
> I have a third party class X that stores and loads its objects using
> std::ostream and std::istream classes. At the same time I'm using X
> objects inside an environment that only allows me to save chunks of
> memory c-style. What I would like to do then is to store X instance in
> std::iostream instance and from that get the underlying array of
> chars. But the problem is I don't know how to determine to size of the
> buffer needed - there is no method of std::istream that returns the
> number of chars used, is it?
The trick is to extend std::basic_streambuf An example I've coded is
template<typename CharType=char,typename
CharTraits=std::char_traits<CharType> >
strct bufreader
:std::basic_streambuf<CharType, CharTraits>
{

typedef typename std::basic_streambuf<CharType, CharTraits>
base_type;
typedef std::streamsize streamsize;
typedef CharType char_type;
typedef CharTraits traits_type;
typedef typename traits_type::int_type int_type;
typedef typename traits_type::off_type off_type;

typedef typename base_type::pos_type pos_type;
bufreader( char_type *beg, char_type *end){
this->setg(beg,beg,end);
}
bufreader( char_type *beg, streamsize end){
this->setg(beg,beg,beg+end);
}
pos_type seekoff(off_type _off,
std::ios_base::seekdir ,std::ios_base::openmode ){
if(_off !=0)
this->setg(this->eback(),this->gptr()+_off,this->egptr());
return (this->gptr())-(this->eback());
}
pos_type seekpos(pos_type _off,std::ios_base::openmode ){
if(_off )
this->setg(this->eback(),this->gptr()+_off,this->egptr());
return (this->gptr())-(this->eback());
}
} ;

Usage: (I hope I typed this up correctly)
char buf[]="Existing buffer of stuff";
bufreader<> bufr(buf,sizeof(buf)-1);
std::istream bufstream(&bufr);
std::vector<std::string> toks;
std::istream_iterator<char> begin(bufstream),end;
std::copy(begin,end,back_inserter(toks));

you should have toks.size()==4

The ostream case is just as easy, except of course you use setp rather
than setg

Lance


--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]