Search code examples
winapihttp-redirectconsole-application

How do I detect when output is being redirected?


I have a Win32 application written in C that can have its console output via printf() redirected to a log file.

It would be nice if I could have my app detect if it had been started with or without a redirect >.

Any ideas?


Solution

  • Tom, thanks for the input.

    I did some experiments and found this works for me..

    fpos_t pos ;
    
    fgetpos (stdout, & pos) ;
    

    When an application's output is being redirected to a file, fgetpos() sets pos to zero. It makes sense since its freshly opened stderr for you.
    EDIT: Actually, the value returned may be a positive integer if text has already been redirected to the log/file. So in your code you'd have something like if (pos >= 0) bfRedirected = TRUE;

    When an application's output is not being redirected - it's going to the console device - not a file, so fgetpos() will set pos to -1.