9

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

Jack
  • 131,802
  • 30
  • 241
  • 343
  • You might want to add some more detail, what happens when you do the final freopen()? Does it return NULL? – unwind Nov 04 '09 at 13:40

2 Answers2

13

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()");
    }
Vinit Dhatrak
  • 6,814
  • 8
  • 27
  • 30
  • 1
    Modifying this to #include and then check the return values on the fgetpos/fsetpos calls shows problems on Linux: if (fgetpos(stdout, &pos)) perror("fgetpos"); – Rhys Ulerich Dec 20 '10 at 18:48
-1

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.

Nick Meyer
  • 39,212
  • 14
  • 67
  • 75
  • 2
    Probably because a (lot of) code is writing without specifying an output stream, e.g. using just plain printf() calls. Redirecting stdout is then a way of "wrapping" that code and making it write to the desired place, without changing it. Just guessing, of course. – unwind Nov 04 '09 at 13:36
  • 1
    @unwind your guess is correct, this is the most likely usecase of freopen. – Vinit Dhatrak Nov 04 '09 at 14:06
  • I can actually confirm that this is the reason. It is a compiler and I always used printf to print asm code (eg. MOV $1, 4.5f) while creating it and now I don't want to waste time replacing things.. – Jack Nov 04 '09 at 14:09
  • A simple `sed` or `perl` script to do all the replacements and fix the broken code would be a lot better than these ugly hacks. – R.. GitHub STOP HELPING ICE Mar 10 '11 at 14:42