printf到控制台窗口和文件? [英] printf to both console window and file?

查看:222
本文介绍了printf到控制台窗口和文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有许多使用Visual Studio 2005编译的C ++程序。它们大多是在控制台窗口中运行的小型服务器模块。无论如何,我遇到的问题是文本只能显示在控制台窗口或日志文件中,而不能同时显示在两者上。每个程序都有一个命令行选项来指定日志文件。这是我调用将stdout和stderr重定向到文件的函数。

I have a lot of C++ programs that compile with Visual Studio 2005. They're mostly small server modules that run in console windows. Anyway, the problem I'm running into is that text can only be displayed to either the console window or a log file but not both. Each program has a command line option to specify the log file. Here is the function that I call to redirect stdout and stderr to a file.

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

有没有办法设置东西up stdout和stderr同时写入两个控制台窗口和一个可选的日志文件?我已经看到重定向cout或包装函数的代码,但是我们的print语句都使用printf,我更喜欢使用类似于consoleobj库中的函数来设置它,如果可能的话。谢谢!

Is there any way to set things up so stdout and stderr are written to both the console window and an optional log file simultaneously? I've seen code that redirects cout or a wrapper function, but our print statements all use printf and I'd prefer using a function similar to the one in our consoleobj library to set this up if possible. Thanks!

推荐答案

而不是在代码中实现此功能。

您可以使用众所周知的实用程序在Unix中 tee

有一个名为的Windows版本 wtee.exe

Instead of implement this functionality in your code.
You can use the well known utility tee in Unix.
There is a Windows version of it called wtee.exe.

C:\> programm | wtee log.txt

这篇关于printf到控制台窗口和文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆