【问题标题】:stdout redirect fails with wprintf()标准输出重定向失败并出现 wprintf()
【发布时间】:2012-08-01 14:18:13
【问题描述】:

以下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

【问题讨论】:

  • fwide 是否与此处相关?
  • 感谢您的指点,将查看它。
  • 也许在存储的文件描述符上尝试fdopen
  • 实际上,你为什么要搞乱文件描述符呢?你可以用fopenfreopen做任何事情,最后只需要fdopen一次就可以恢复原始输出。
  • 即使您以./main &gt; blah.log 运行可执行文件会怎样。你能保证stdout会被放回blah.log

标签: c stdout io-redirection


【解决方案1】:

问题是由于标准输出的方向。 在调用 wprintf() 之前,使用 mode=0 调用 fwide() 并检查它是否返回 +ve 值。如果是这样,您可以安全地使用 wprintf()。 使用完 wprintf() 后,关闭标准输出并重新打开它以再次使用普通的 printf()。 或者,此后继续在现有标准输出上使用 wprintf() 和宽字符函数。 一旦标准输出有一个方向(字节或宽),它就不能被改变并持续存在直到它被关闭。

【讨论】:

  • 你对stdout的方向是正确的。看来你不能在一个程序中混合使用wprintfprintf 调用。
  • 我不确定如何关闭并重新打开 stdout 以指向它所在的位置。
  • 看看:stackoverflow.com/questions/9084099/… 以及重新打开()系统调用的手册。
猜你喜欢
  • 2013-10-09
  • 2018-04-05
  • 1970-01-01
  • 1970-01-01
  • 2014-01-20
  • 2011-12-08
  • 2012-08-15
  • 1970-01-01
相关资源
最近更新 更多