【问题标题】:printf to both console window and file?printf 到控制台窗口和文件?
【发布时间】: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


【解决方案1】:

而不是在您的代码中实现此功能。
您可以在 Unix 中使用众所周知的实用程序 tee
它有一个 Windows 版本,称为 wtee.exe

C:\> programm | wtee log.txt

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-14
    • 1970-01-01
    • 2012-06-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多