Redirecting stdout

Robert Fraser fraserofthenight at gmail.com
Tue Dec 4 20:00:07 PST 2007


Bill Baxter wrote:
> Robert Fraser wrote:
>> I'd like at a particular point in my program to temporarily ignore all 
>> stdout (i.e. not have it written to the stream)... is there a way to 
>> do this? I want my program to work under both Phobos & Tango, so a way 
>> for both libraries would be great.
>>
> 
> Phobos just uses the underlying C stream objects in the end, so you can 
> use freopen on those.  Note that std.cstream functions will throw 
> exceptions if the standard output streams are not open, so the code 
> below freopens them to point to /dev/null or Nul.
> 
> Don't know if there's a better way, but this way has been working for me.
> 
> version(Tango) {
>     ??
> }
> else {
>     static this() {
>         // redefine dout,derr,dlog to prevent IO exceptions
>         version(Windows) {
>             std.c.stdio.freopen("Nul", "w", dout.file);
>             std.c.stdio.freopen("Nul", "w", derr.file);
>         }
>         else {
>             std.c.stdio.freopen("/dev/null", "w", dout.file);
>             std.c.stdio.freopen("/dev/null", "w", derr.file);
>         }
>     }
> }

Thanks; that's what I needed! But how do I capture the current 
stdout/stderr so I can get them back (I've never done these scary stream 
thing before, obviously).


More information about the Digitalmars-d-learn mailing list