Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I needed to forward stdout to different files to separate some prints produced and the reverting back to normal stdout.

I used freopen to switch to the file in this way:

char name[80];
memset(name, 0, 80);
strcpy(name, "./scripts/asm/");
strcat(name, m_func->m_name->m_value);
strcat(name, ".shasm");
freopen(name, "w", stdout);

And it actually works, but at the end of the process (mind that stdout is redirected many times in the previous same way) I'm not able to revert it to original stdout. I tried the following:

freopen("/dev/stdout", "w", stdout);

but it doesn't seem to work.. just for information I'm developing on macosx.

What should I do?

Thanks in advance

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
399 views
Welcome To Ask or Share your Answers For Others

1 Answer

This can be achieved using fileno, dup and dup2 calls. I have tried this on linux not sure whether this will work on mac but I am sure you will get some equivalent functions for your setup. See if this sample code works for you. Sorry for lack of error-handling in the code. :)

    #include <stdio.h>

    main()
    {
        int    fd;
        fpos_t pos;

        printf("stdout, ");

        fflush(stdout);
        fgetpos(stdout, &pos);
        fd = dup(fileno(stdout));
        freopen("stdout.out", "w", stdout);

        f();

        fflush(stdout);
        dup2(fd, fileno(stdout));
        close(fd);
        clearerr(stdout);
        fsetpos(stdout, &pos);        /* for C9X */

        printf("stdout again
");
    }

    f()
    {
    printf("stdout in f()");
    }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...