#include <fstream>
#include <vector>
#include <iostream>
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<char> m_tableBuffer;
double dValue = 1.2345;
const void* dBytes = &dValue;
std::copy(static_cast<const char *>(dBytes), static_cast<const char *>(dBytes) + sizeof(double), std::back_inserter(m_tableBuffer));
outstream.write((char*)m_tableBuffer.data(), m_tableBuffer.size());
if (!bWriteConsole)
outfile.close();
else
std::cout << std::flush;
return 0;
}
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.
Question> Is there any issue with this implementation? Is there an elegant solution without considering RAII?
Thank you
== Updated based on comments from luk32
void function2()
{
bool bWriteConsole = true;
std::ofstream outfile;
if (!bWriteConsole)
outfile.open("./hello.bin", std::ofstream::binary | std::ofstream::out);
std::vector<char> m_tableBuffer;
double dValue = 1.2345;
const void* dBytes = &dValue;
std::copy(static_cast<const char *>(dBytes), static_cast<const char *>(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();
}
}