Monday, April 28, 2014

dup2

Newsgroup: comp.lang.c++

Subject: dup2

From: Hongliang Wang <loudking@...>

Date: Tue, 22 Apr 2014 01:35:06 -0700 (PDT)



Hell all,



I was trying to redirect stdout to a file by using dup2. First I followed microsoft example: http://ift.tt/1iy7o06



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();

}







via Usenet Forums - Usenet Search,Free Usenet - comp.lang.c++ http://ift.tt/1hKJ0mS

View all the progranning help forums at:

http://ift.tt/1dP9txN

No comments:

Post a Comment