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

前端 未结 6 1013
说谎
说谎 2021-02-15 15:51

What I want to do

redirect stdout and stderr to one or more files from inside c++

Why I need it

I am using an external, pr

6条回答
  •  醉梦人生
    2021-02-15 16:13

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

提交回复
热议问题