disabling and enabling console output

Alex AJ at gmail.com
Thu May 16 17:05:01 UTC 2019


On Thursday, 16 May 2019 at 15:21:48 UTC, Vladimir Panteleev 
wrote:
> On Thursday, 16 May 2019 at 14:53:14 UTC, Alex wrote:
>> I have some code that disables the console because some other 
>> code puts junk on it that I don't want to see... then I enable 
>> it.
>
> One thing you could try is going one level lower, and using 
> dup() to save the stream to another fd, close() to close the 
> stdout one, and dup2() to restore the saved fd over the stdout 
> one.

Unfortunately D doesn't seem to have dup, dup2.

On 05/10/14 22:24, MarisaLovesUsAll via Digitalmars-d-learn wrote:
> I sometimes got a useless messages in stdout from SDL_Image 
> library, and I want to temporary silence it. How do I do?

One way would be something like:

    import std.stdio;

    void writeOutput () {
       static c = 1;
       printf("%d\n", c++);
    }

    void main() {
       writeOutput();

       {
          auto ex = PushFD!1("/dev/null".ptr);
          writeOutput();
       }

       writeOutput();
    }

    struct PushFD(int fd) {
       import core.sys.posix.fcntl, core.sys.posix.unistd;
       int old;
       this(const char* fn) { //
          old = dup(fd);
          auto nfd = open(fn, O_RDWR);
          dup2(nfd, fd);
          close(nfd);
       }
       ~this() { dup2(old, fd); close(old); }
    }

// In real code you'll want to check for errors from 
dup/dup2/open/close.

artur

That code fails to compile on windows.


More information about the Digitalmars-d-learn mailing list