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