views:

186

answers:

4

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?

A: 

AFAIK the answer to this is that you can't. Output redirection works by simply reading the stream of output from a given program and redirecting it to another pipe / stream. The design of file / streams is such that the writer is ignorant of the reader to the point that you shouldn't know you are being read.

Even detecting that there was a reader would be of no use because there is one in the normal case. The console is reading the output of your program and displaying it to the screen already.

JaredPar
+1  A: 

I think that pipes are blind by nature, so you don't have a built-in way to tell whether you're being redirected. Moreover, trying to find out what's happening behind an abstraction layer is a bad habit.

If you really need to control your output, add the log file name as a command line parameter!

That being said, you can make some smart guesswork to find out:

  • A program can query the shell command history to find out the most recent commands executed.
  • If you know the path to the logfiles, you can scan that directory and see if a file has been created or changed its size.
  • Benchmark writing speed when redirected and not redirected. This would work only if your system is ultra-stable, and environment condition won't change.
Adam Matan
+2  A: 

There may be a way to do this - a quick google yielded this hit that might give you the hint in the right direction.

Hope this helps, Best regards, Tom.

tommieb75
+1 Nice answer. Have you tried it?
Adam Matan
@Adam: Actually, that surprised me, so no, I have not tried it. I didn't think it was possible either! :)
tommieb75
+1  A: 

Tom, thanks for the input.

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

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

logout