freopen stdout and console

前端 未结 3 845
梦如初夏
梦如初夏 2020-12-16 03:32

Given the following function:

freopen(\"file.txt\",\"w\",stdout);

Redirects stdout into a file, how do I make it so stdout redirects back i

相关标签:
3条回答
  • 2020-12-16 04:03

    You should be able to use _dup to do this

    Something like this should work (or you may prefer the example listed in the _dup documentation):

    #include <io.h>
    #include <stdio.h>
    
    ...
    {
        int stdout_dupfd;
        FILE *temp_out;
    
        /* duplicate stdout */
        stdout_dupfd = _dup(1);
    
        temp_out = fopen("file.txt", "w");
    
        /* replace stdout with our output fd */
        _dup2(_fileno(temp_out), 1);
        /* output something... */
        printf("Woot!\n");
        /* flush output so it goes to our file */
        fflush(stdout);
        fclose(temp_out);
        /* Now restore stdout */
        _dup2(stdout_dupfd, 1);
        _close(stdout_dupfd);
    }
    
    0 讨论(0)
  • 2020-12-16 04:11

    An alternate solution is:

    freopen("CON","w",stdout);
    

    Per wikipedia "CON" is a special keyword which refers to the console.

    0 讨论(0)
  • 2020-12-16 04:11

    After posting the answer I have noticed that this is a Windows-specific question. The below still might be useful in the context of the question to other people. Windows also provides _fdopen, so mayble simply changing 0 to a proper HANDLE would modify this Linux solution to Windows.

    stdout = fdopen(0, "w")

    #include <stdio.h>
    #include <stdlib.h>
    int main()
    {
        freopen("file.txt","w",stdout);
        printf("dupa1");
        fclose(stdout);
        stdout = fdopen(0, "w");
        printf("dupa2");
        return 0;
    }
    
    0 讨论(0)
提交回复
热议问题