Re: freopen on both stdout and stderr



Mark Bluemel wrote, On 23/11/07 12:01:
Guillaume Dargaud wrote:
Hello all,
a while ago I was pointed towards freopen as a way to redirect stderr to a log file. It works great, but apparently the app also writes a few lines to stdout. Now I could redirect to 2 separate files, but would rather keep the 2 flows together.

Is it correct to do this:
stderr=freopen(LogFile, "w", stderr);
stdout=freopen(LogFile, "a", stdout);

It's not in accordance with the standard to do this, as "stderr" and "stdout" are not, as I recall, guaranteed to be lvalues...

If you can assign them, and you're prepared to accept non-portability, then you could perhaps try the following, untested, hackery

stderr=freopen(LogFile, "w", stderr);
fclose(stdout);
stdout=stderr;

Otherwise, I'm not convinced you have many options available to you.

Personally I would use a mechanism outside the program in order to achieve this and not redirect either stdout or stderr within the program. E.g.
prog >log 2>&1
The precise mechanism (and whether it is even possible) is dependant on the system being used.
--
Flash Gordon
.



Relevant Pages

  • Re: freopen on both stdout and stderr
    ... Guillaume Dargaud wrote: ... a while ago I was pointed towards freopen as a way to redirect stderr to a log file. ... but apparently the app also writes a few lines to stdout. ...
    (comp.lang.c)
  • Re: Redirecting STDOUT
    ... output of stdout redirected to a file. ... impression the following would redirect stdout to a file, ... This is highly shell dependent but on ksh, this command works. ... The above command will redirect stderr to the bit bucket and ...
    (freebsd-questions)
  • MIME::Lite debugging
    ... I am trying to take any debug output and send it through a Debug ... function which goes to a log file so I can see if there is an error. ... I'm not using die because I think that sends it to stdout. ... I redirect it into a string variable or something that allows me to ...
    (perl.beginners)
  • Re: How to get log file for rsync operation? Does rsync also delete remote files?
    ... When I read the rsync manual it does not become clear on how to write a log file for the rsync operation. ... You can redirect stderr and stdout to a logfile. ...
    (comp.os.linux.networking)
  • Re: [OT] Cant redirect before fork().
    ... log file, but it's not working. ... close STDOUT; ... I shouldn't redirect from within the child, ...
    (perl.beginners)