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
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!
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
.