1

We all know there're two way to redirected the standard output.

First, we can use freopen_s to redirected the stdout and stderr to a file.

Second, we can redirected the stdout and stderr when we call the executable file like this: xxx.exe > log.txt 2>&1.

So my problem is that how can I know where the stdout and stderr has been redirected.

I met this problem in my program in such a situation: If the user redirected the standart output by the second way, I should redirected it to "CON", and print some logs to the console. If the user didn't redirect it, I should not print these logs to the console.

This is because if the user didn't redirected it, these logs had already be printed to the console.

FPanda
  • 29
  • 2
  • 7
  • That looks like an awkward requirement. I'd avoid it altogether. – Amit Sep 11 '15 at 06:18
  • 1
    This seems a little backward. If the user redirected your output on purpose, printing to the console anyway is probably not what the user wants? – melak47 Sep 11 '15 at 06:19
  • In general, this is impossible. Also, this has been asked already, there might be possibilities to get SOME info about your output stream, depending on the operating system –  Sep 11 '15 at 06:19
  • OS-specific. The keyword you are looking for is "`isatty`" if you are on POSIX. – cnicutar Sep 11 '15 at 06:20

1 Answers1

1

You cannot detect where it is being directed, but if.

On Posix systems, use isatty():

#include <stdio.h>
#include <io.h>
...    
if (isatty(fileno(stdin)))
    printf( "stdin is a terminal\n" );
else
    printf( "stdin is a file or a pipe\n");

On Windows, use _isatty().

anorm
  • 2,255
  • 1
  • 19
  • 38
  • 1
    `isatty` isn't very reliable on systems that have `CON` and `.exe` and stuff. – n. m. could be an AI Sep 11 '15 at 06:30
  • 2
    In Windows, you can, in a somewhat convoluted way. Call `_get_osfhandle(1)` to get the `HANDLE` to stdout, and then `GetFinalPathNameByHandle()` to find out where it points. – rodrigo Sep 11 '15 at 06:33
  • @rodrigo It's possible in Plan 9, too, but we can only guess OPs operating system. – fuz Sep 11 '15 at 07:39
  • @FUZxxl: Well, I was talking about those systems with `CON` and `.exe` stuff. – rodrigo Sep 11 '15 at 07:45
  • @rodrigo There's more than one operating system where the file extension for a program is `exe` and more than one operating system where you can redirect to `CON`. If OP wants us to give platform specific help, he should specify his platform. – fuz Sep 11 '15 at 07:47
  • @FUZxxl: Sure, and maybe `freopen_s()` too, and that's why I write a comment and not an answer. But if the OS were using some unusual system they are likely to comment it. I'd be willing to bet that the OP is using some version of Windows. – rodrigo Sep 11 '15 at 07:57