【发布时间】:2013-09-24 07:31:20
【问题描述】:
我有一个需求,我还需要使用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(caps,上面代码的注释部分) 中完成了它。但是我想使用普通的std::cout,那么我该如何覆盖它。它应该适用于sting and variables 之类的
int i = 5;
cout << "Hello world" << i <<endl;
或者无论如何要捕获stdout数据,以便它们也可以轻松写入file and console。
【问题讨论】:
-
@nijansen:确实非常邪恶。
-
@nijansen:废话,定义明确的机制:.rbduf()
-
@nijansen 您可以只替换 main 中的
cout缓冲区。是的,这仍然不适用于在 main 之前初始化的每个对象,但也许这不是问题。 -
“错误”的评论还有效吗?它似乎与您当前的问题无关
-
printf的代码是未定义的行为。不允许在标准库中重新定义函数。
标签: c++ windows visual-studio-2010