How could I temporary redirect stdout to a file in a C program?

后端 未结 1 1411
梦谈多话
梦谈多话 2020-11-30 00:45

Within my C program, I’d like to temporarly redirect stdout to /dev/null (for example). Then, after writing to /dev/null, I’d like to restore stdou

相关标签:
1条回答
  • 2020-11-30 01:11

    On POSIX systems, you can do it as follows:

    int bak, new;
    
    fflush(stdout);
    bak = dup(1);
    new = open("/dev/null", O_WRONLY);
    dup2(new, 1);
    close(new);
    
    /* your code here ... */
    
    fflush(stdout);
    dup2(bak, 1);
    close(bak);
    

    What you want is not possible in further generality.

    Any solution using freopen is wrong, as it does not allow you to restore the original stdout. Any solution by assignment to stdout is wrong, as stdout is not an lvalue (it's a macro that expands to an expression of type FILE *).

    0 讨论(0)
提交回复
热议问题