【发布时间】:2012-03-27 02:34:33
【问题描述】:
我有很多用 Visual Studio 2005 编译的 C++ 程序。它们大多是在控制台窗口中运行的小型服务器模块。无论如何,我遇到的问题是文本只能显示到控制台窗口或日志文件,但不能同时显示。每个程序都有一个命令行选项来指定日志文件。这是我调用的将 stdout 和 stderr 重定向到文件的函数。
void consoleobj::setstdouterr(const stringobj& printstr)
{
#if !defined(_WIN32_WCE)
freopen(printstr.c_str(),"w",stdout);
#ifdef _MSC_VER
::SetStdHandle(STD_ERROR_HANDLE,GetStdHandle(STD_OUTPUT_HANDLE));
#endif
#endif
// make log msgs flush to log file(cout does this(on \n?), printf doesn't)
//now if both redir to same log file, msgs should be in right order
setvbuf(stdout, NULL, _IONBF, 0); //no buffering
setvbuf(stderr, NULL, _IONBF, 0); //no buffering
}//end method setstdouterr
有没有什么方法可以将 stdout 和 stderr 同时写入控制台窗口和可选的日志文件?我见过重定向 cout 或包装函数的代码,但我们的打印语句都使用 printf,如果可能的话,我更喜欢使用类似于我们的 consoleobj 库中的函数来设置它。谢谢!
【问题讨论】:
-
dup2()在 Windows 下工作吗?
标签: c++ visual-studio-2005 io