freopen: reverting back to original stream

后端 未结 2 1254
日久生厌
日久生厌 2020-12-10 05:39

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

相关标签:
2条回答
  • 2020-12-10 06:07

    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\n");
        }
    
        f()
        {
        printf("stdout in f()");
        }
    
    0 讨论(0)
  • 2020-12-10 06:34

    This seems like a roundabout way of solving your problem. Why not just open each file with fopen() and then writing to its FILE * with fputs, fprintf, fwrite etc? No need to redirect stdout.

    0 讨论(0)
提交回复
热议问题