以下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()");
}
可以很好地重定向 stdout
然后将其放回去。但是,将 f()
更改为:
f()
{
wprintf(L"stdout in f()");
}
不允许恢复标准输出。有人知道为什么会这样吗?
[matt test] uname -r
3.4.6-2.fc17.x86_64
最佳答案
问题是由于标准输出的方向。 在调用 wprintf() 之前调用带有 mode=0 的 fwide() 并检查它是否返回 +ve 值。如果是这样,您可以安全地使用 wprintf()。 使用完 wprintf() 后,关闭标准输出并重新打开它以再次使用正常的 printf()。 或者,此后继续在现有标准输出上使用 wprintf() 和宽字符函数。 一旦 stdout 有一个方向(字节或宽度),它就不能更改并一直存在,直到它关闭。
关于c - 标准输出重定向因 wprintf() 而失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11761266/