我有一个要求,我需要使用printf
和cout
将数据也显示为console and file
。
对于printf
,我已经做到了,但是对于cout
,我却在努力,该怎么做?
#ifdef _MSC_VER
#define GWEN_FNULL "NUL"
#define va_copy(d,s) ((d) = (s))
#else
#define GWEN_FNULL "/dev/null"
#endif
#include <iostream>
#include <fstream>
using namespace std;
void printf (FILE * outfile, const char * format, ...)
{
va_list ap1, ap2;
int i = 5;
va_start(ap1, format);
va_copy(ap2, ap1);
vprintf(format, ap1);
vfprintf(outfile, format, ap2);
va_end(ap2);
va_end(ap1);
}
/* void COUT(const char* fmt, ...)
{
ofstream out("output-file.txt");
std::cout << "Cout to file";
out << "Cout to file";
}*/
int main (int argc, char *argv[]) {
FILE *outfile;
char *mode = "a+";
char outputFilename[] = "PRINT.log";
outfile = fopen(outputFilename, mode);
char bigfoot[] = "Hello
World!\n";
int howbad = 10;
printf(outfile, "\n--------\n");
//myout();
/* then i realized that i can't send the arguments to fn:PRINTs */
printf(outfile, "%s %i",bigfoot, howbad); /* error here! I can't send bigfoot and howbad*/
system("pause");
return 0;
}
我已经在
COUT
(大写,上面的代码的注释部分)中完成了此操作。但是我想使用普通的std::cout
,所以如何覆盖它。它应该适用于sting and variables
这样的int i = 5;
cout << "Hello world" << i <<endl;
或者无论如何都可以捕获
stdout
数据,以便它们也可以轻松地写入file and console
中。 最佳答案
覆盖std::cout
的行为是一个非常糟糕的主意,因为其他开发人员将很难理解std::cout
的使用不会像往常一样。
上一堂简单的课就可以使你清楚
#include <fstream>
#include <iostream>
class DualStream
{
std::ofstream file_stream;
bool valid_state;
public:
DualStream(const char* filename) // the ofstream needs a path
:
file_stream(filename), // open the file stream
valid_state(file_stream) // set the state of the DualStream according to the state of the ofstream
{
}
explicit operator bool() const
{
return valid_state;
}
template <typename T>
DualStream& operator<<(T&& t) // provide a generic operator<<
{
if ( !valid_state ) // if it previously was in a bad state, don't try anything
{
return *this;
}
if ( !(std::cout << t) ) // to console!
{
valid_state = false;
return *this;
}
if ( !(file_stream << t) ) // to file!
{
valid_state = false;
return *this;
}
return *this;
}
};
// let's test it:
int main()
{
DualStream ds("testfile");
if ( (ds << 1 << "\n" << 2 << "\n") )
{
std::cerr << "all went fine\n";
}
else
{
std::cerr << "bad bad stream\n";
}
}
这提供了一个干净的界面,并为控制台和文件输出了相同的界面。
您可能想要添加刷新方法或以追加模式打开文件。
关于c++ - 如何在C++中覆盖cout?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/18975512/