H
Hongliang Wang
Hell all,
I was trying to redirect stdout to a file by using dup2. First I followed microsoft example: http://msdn.microsoft.com/en-us/library/8syseb29.aspx
it just works fine.
Then I tried to implement this in my own class (ABCLog) but stdout is not captured. I cannot figure it out. The only reason I could think of is that main() is in main.cpp while class ABCLog are in separate files (ABCLog.cpp and ABCLog.h). Could anybody confirm this please?
int main(int argc, char *argv[])
{
ABCLog *log = new ABCLog();
puts("in main");
fflush( stdout );
delete log;
return 0;
}
ABCLog::ABCLog(const char *logFileName)
{
old = _dup(1); /* "old" refers to stdout */
if(old == -1) {
perror(ERR_000104_DUP);
exit(1);
}
if( fopen_s( &logFile, logFileName, "a" ) != 0 ) {
fprintf(stderr, ERR_000105_LOG_FILE_OPEN, logFileName);
exit( 1 );
}
if( -1 == _dup2( _fileno( logFile ), 1 ) ) {
perror( ERR_000106_DUP2 );
exit( 1 );
}
puts("in ABCLog");
fflush(stdout);
}
/**
* Destructor
*/
ABCLog::~ABCLog()
{
_dup2( old, 1 );
_flushall();
m_stream.close();
}
I was trying to redirect stdout to a file by using dup2. First I followed microsoft example: http://msdn.microsoft.com/en-us/library/8syseb29.aspx
it just works fine.
Then I tried to implement this in my own class (ABCLog) but stdout is not captured. I cannot figure it out. The only reason I could think of is that main() is in main.cpp while class ABCLog are in separate files (ABCLog.cpp and ABCLog.h). Could anybody confirm this please?
int main(int argc, char *argv[])
{
ABCLog *log = new ABCLog();
puts("in main");
fflush( stdout );
delete log;
return 0;
}
ABCLog::ABCLog(const char *logFileName)
{
old = _dup(1); /* "old" refers to stdout */
if(old == -1) {
perror(ERR_000104_DUP);
exit(1);
}
if( fopen_s( &logFile, logFileName, "a" ) != 0 ) {
fprintf(stderr, ERR_000105_LOG_FILE_OPEN, logFileName);
exit( 1 );
}
if( -1 == _dup2( _fileno( logFile ), 1 ) ) {
perror( ERR_000106_DUP2 );
exit( 1 );
}
puts("in ABCLog");
fflush(stdout);
}
/**
* Destructor
*/
ABCLog::~ABCLog()
{
_dup2( old, 1 );
_flushall();
m_stream.close();
}