1

The following 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()");
}

Works fine to redirect stdout and then put it back. However, changing f() to:

f()
{
    wprintf(L"stdout in f()");
}

Will not allow the stdout to be restored. Anyone know why this may be the case?

[matt test] uname -r
3.4.6-2.fc17.x86_64
Matt Clarkson
  • 14,106
  • 10
  • 57
  • 85

1 Answers1

2

The problem is due to the orientation of the stdout. Before calling wprintf() call fwide() with mode=0 and check if it returns a +ve value. If it does, you can use wprintf() safely. And after you are done using wprintf(), close the stdout and re-open it to use normal printf() again. Or, continue using wprintf() and wide character functions on the existing stdout, thereafter. Once the stdout has an orientation(byte or wide), it cannot be changed and persists until it is closed.

askmish
  • 6,464
  • 23
  • 42
  • You are correct about the orientation of `stdout`. It seems you cannot mix `wprintf` and `printf` calls in a program. – Matt Clarkson Aug 01 '12 at 14:55
  • I'm not sure how to close and reopen stdout to point to the same place it was in. – Matt Clarkson Aug 01 '12 at 15:15
  • Take a look at: http://stackoverflow.com/questions/9084099/re-opening-stdout-and-stdin-file-descriptors-after-closing-them and also at the manual for reopen() system call. – askmish Aug 02 '12 at 06:59