Note that there are some explanatory texts on larger screens.

plurals
  1. POUse multiple ofstreams to write to a single output file in c++
    primarykey
    data
    text
    <p>I have class <code>Writer</code> that has two <code>ofstream</code> members.<br/> Both streams are associated with the <strong>same</strong> output file. I'd like to use both streams in <code>Writer::write</code> method, but to make sure that each stream writes to the end of the real output file.<br/></p> <p><em><strong>Code</em></strong></p> <pre><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(); } </code></pre> <p><em><strong>Questions</em></strong><br/><br/> How to ensure <code>f2</code> is in sync with <code>f1</code>? meaning, before writing, stream offset of <code>f2</code> must be in sync with stream offset of <code>f1</code> and vice versa?<br/> I can't use function <a href="http://www.cplusplus.com/reference/ios/ios/rdbuf/" rel="nofollow">std::ios::rdbuf</a> since each <code>ofstream</code> uses special derived <code>streambuf</code>. so by using <code>rdbuf()</code> I'll lose the necessary functionality.<br/> I tried using some of the techniques found in <a href="http://www.math.hkbu.edu.hk/parallel/pgi/doc/pgC++_lib/stdlibug/syn_4687.htm" rel="nofollow">Synchronizing Streams</a> topic but could not make it happen.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload