title: Good practice to write binary stream to either a file or stdout
body: <pre><code>#include &lt;fstream&gt; 
  #include &lt;vector&gt;
  #include &lt;iostream&gt;
  
  int main()
  {
      bool bWriteConsole = true;
      std::streambuf *buf;
      std::ofstream outfile;
  
      if (bWriteConsole)
          buf = std::cout.rdbuf();
      else
      {
          outfile.open("./hello.bin", std::ofstream::binary | std::ofstream::out);
          buf = outfile.rdbuf();
      }
  
      std::ostream outstream(buf);
      std::vector&lt;char&gt; m_tableBuffer;
      double dValue = 1.2345;
      const void* dBytes = &amp;dValue;
      std::copy(static_cast&lt;const char *&gt;(dBytes), static_cast&lt;const char *&gt;(dBytes) + sizeof(double), std::back_inserter(m_tableBuffer));
  
      outstream.write((char*)m_tableBuffer.data(), m_tableBuffer.size());
  
      if (!bWriteConsole)
          outfile.close();
      else
          std::cout &lt;&lt; std::flush;
  
      return 0;
  }
  </code></pre>
  
  <p>I need to add a function to my existing application so that it can output the binary stream to stdout instead of file. The prototype is shown above. </p>
  
  <p>Question> Is there any issue with this implementation? Is there an elegant solution without considering RAII?</p>
  
  <p>Thank you</p>
  
  <p>== Updated based on comments from luk32</p>
  
  <pre><code>void function2()
  {
      bool bWriteConsole = true;
      std::ofstream outfile;
  
      if (!bWriteConsole)
          outfile.open("./hello.bin", std::ofstream::binary | std::ofstream::out);
  
      std::vector&lt;char&gt; m_tableBuffer;
      double dValue = 1.2345;
      const void* dBytes = &amp;dValue;
      std::copy(static_cast&lt;const char *&gt;(dBytes), static_cast&lt;const char *&gt;(dBytes) + sizeof(double), std::back_inserter(m_tableBuffer));
  
      if (!bWriteConsole)
      {
          outfile.write((char*)m_tableBuffer.data(), m_tableBuffer.size());
          outfile.close();
      }
      else
      {
          std::cout.write((char*)m_tableBuffer.data(), m_tableBuffer.size());
          std::cout.flush();
      }
  }
  </code></pre>