将f打印到控制台窗口和文件

printf to both console window and file?

本文关键字:窗口 文件 控制台 打印      更新时间:2023-10-16

我有很多用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或包装函数的代码,但我们的print语句都使用printf,如果可能的话,我更喜欢使用类似于consoleobj库中的函数来设置它。谢谢

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

C:> programm | wtee log.txt