开发者

freopen stdout and console

Given the following function:

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

Redirects stdout into a file, how do I make开发者_高级运维 it so stdout redirects back into the console?

I will note, yes there are other questions similar to this, but they are about linux/posix. I'm using windows.

You can't assigned to stdout, which nullifies one set of solutions that rely on it. dup and dup2() are not native to windows, nullifying the other set. As said, posix functions don't apply (unless you count fdopen()).


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);
}


An alternate solution is:

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

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


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;
}


take note that the filedescriptors for stdin, stdout, stderr (0,1,2) are not nessesarily the same as the 'special variables' printf() and the likes use. although in most cases they output to the same devices upon program start. (not if you start changing things in the middle of your program, or tty redirects are in place). stdin stdout stderr are FILE * pointers. both concepts need to be 'redirected' seperately from each other with their own methods... 'dup2' is for duplicating file descriptors. not FILE pointers. for FILE * pointers such as stdin, stdout, stderr... 'freopen()'.. but that will literally only affect printf and derivatives.


This works to me

#include <stdio.h>
int main()
{

    FILE* original_stdout = stdout;
    stdout = fopen("new_stdout.txt", "w");
    printf("ciao\n");
    fclose(stdout);
    stdout = original_stdout;
    printf("a tutti\n");
    return 0;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜