I have class Writer
that has two ofstream
members.
Both streams are associated with the same output file. I'd like to use both streams in Writer::write
method, but to make sure that each stream writes to the end of the real output file.
Code
class my_ofstream1:
public ofstream
{
// implement some functions.
// using internal, extended type of streambuf
};
class my_ofstream2:
public ofstream
{
// implement some functions.
// using internal, extended type of streambuf
// (not the same type as found in my_ofstream1)
};
class Writer
{
public:
void open(string path)
{
f1.open(path.c_str(),ios_base::out); f2.open(path.c_str(),ios_base::out);
}
void close()
{
f1.close(); f2.close();
}
void write()
{
string s1 = "some string 1";
string s2 = "some string 2";
f1.write(s1.c_str(), s1.size());
// TBD - ensure stream f2 writes to the end of the actual output file
assert(f1.tellp() == f2.tellp());
f2.write(s2.c_str(), s2.size());
}
private:
my_ofstream1 f1;
my_ofstream1 f2;
};
void main()
{
Writer w;
w.open("some_file.txt");
w.write();
w.close();
}
Questions
How to ensure f2
is in sync with f1
? meaning, before writing, stream offset of f2
must be in sync with stream offset of f1
and vice versa?
I can't use function std::ios::rdbuf since each ofstream
uses special derived streambuf
. so by using rdbuf()
I'll lose the necessary functionality.
I tried using some of the techniques found in Synchronizing Streams topic but could not make it happen.
tie()
. It allows you to couple a stream (input or output) to an output stream, such that the output of the tied stream gets flushed. In my quick reading oftie()
, though, it appears the synchronization is only one-way. Otherwise, it seems like you might consider an approach that funnels everything through a common class that serializes and writes everything via the trueofstream
. – Offwhiteofstream
after serialization? I see no reason to push the actual file I/O that far up in the hierarchy. – Offwhiteostream
level. It's at thestreambuf
level that he has to delegate: his custom streambufs should be decorators of a common finalfilebuf
(and not do any buffering themselves). – Cartagena