Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

freopen stdout and console

Tags:

c

windows

stdout

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()).

like image 697
SSight3 Avatar asked Oct 05 '11 16:10

SSight3


2 Answers

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;
}
like image 175
RushPL Avatar answered Sep 27 '22 18:09

RushPL


An alternate solution is:

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

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

like image 33
dtyler Avatar answered Sep 27 '22 18:09

dtyler