redirect stdout/stderr to file under unix c++ - again

In addition to afr0ck answer of freopen() I want to say that while using freopen() we should be careful. Once a stream like stdout or stdin is reopened with assigning the new destination(here the 'output.txt' file) always it remains for a program unless it has been explicitly change.

freopen("output.txt", "a", stdout);

Here the standard output stream stdout is reopened and assigned with the 'output.txt' file. After that whenever we use printf() or any other stdout stream like - putchar() then every output will goes to the 'output.txt'. To get back the default behavior (that is printing the output in console/terminal) of printf() or putchar() we can use the following line of code -

  • for gcc, linux distribution like ubuntu - freopen("/dev/tty", "w", stdout);
  • for Mingw C/C++, windows - freopen("CON", "w", stdout);

See the code example below -

#include <stdio.h>

int main() {
    
    printf("No#1. This line goes to terminal/console\n");

    freopen("output.txt", "a", stdout);
    printf("No#2. This line goes to the \"output.txt\" file\n");
    printf("No#3. This line aslo goes to the \"output.txt\" file\n");

    freopen("/dev/tty", "w", stdout); /*for gcc, diffrent linux distro eg. - ubuntu*/
    //freopen("CON", "w", stdout); /*Mingw C++; Windows*/
    printf("No#4. This line again goes to terminal/console\n");        

}

This code generate a 'output.txt' file in your current directory and the No#2 and No#3 will be printed in the 'output.txt' file.

Thanks


If you want to be able to reuse it, don't close stdoutfd in restore_stdout.