我有一个需求,需要使用printf
和cout
将数据显示在控制台和文件
中。
对于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
,那么我该如何覆盖它呢?并且它应该对 字符串和变量
都有效。
int i = 5;
cout << "Hello world" << i <<endl;
或者有没有办法捕获 stdout
数据,以便它们可以轻松地写入 文件和控制台
。
cout
缓冲区。是的,这仍然不能解决每个在 main 函数之前初始化的对象的问题,但也许这不是一个问题。 - RedX