#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;
}
我需要向现有应用程序中添加一个函数,以便它可以将二进制流输出到stdout而不是文件。原型如上所示。
问题>此实现是否存在任何问题?有没有考虑RAII的优雅解决方案?
谢谢
==根据来自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();
}
}
答案 0 :(得分:1)
我的版本更类似于此:
#include <iostream>
#include <fstream>
void function2(bool bWriteConsole)
{
std::ofstream outfile;
if (!bWriteConsole)
outfile.open("./hello.bin", std::ofstream::binary | std::ofstream::out);
double dValue = 1.2345;
// writing out
std::ostream& out = bWriteConsole ? std::cout : outfile;
out.write(reinterpret_cast<char*>(&dValue), sizeof dValue);
out.flush();
}
编写代码为2行,如果您确实要刷新,则为3行。 outfile.close()
也将刷新,因此与您的方法相比,无条件刷新不会有任何危害。当outfile
超出范围时,文件将关闭,因此不必写入文件,除非您真的想在进行进一步处理之前手动关闭文件。在这里是多余的(RAII的优点在这里发挥了作用。)
Aaand可能重构写作:
template<typename T>
void dump(T val, std::ostream& out ) {
out.write(reinterpret_cast<char*>(&val), sizeof val);
out.flush();
}
void function2(bool bWriteConsole)
{
std::ofstream outfile;
if (!bWriteConsole)
outfile.open("./hello.bin", std::ofstream::binary | std::ofstream::out);
double dValue = 1.2345;
dump(dValue, bWriteConsole ? std::cout : outfile);
// writing out
}