答案 A
上面的答案都没有指出为什么您可能看不到某些打印件。这也是因为您在这里处理的是流(我不知道这一点)并且流有一种叫做方向的东西。让我从这个来源引用一些东西:
窄方位和宽方位
新打开的流没有方向。第一次调用任何 I/O 函数都会确定方向。
宽 I/O 功能使流
面向宽,窄 I/O 功能使流面向窄。设置后,只能使用freopen更改方向。
窄 I/O 函数不能在面向宽的流上调用;宽 I/O 函数不能在面向窄的流上调用。宽 I/O 函数在宽字符和多字节字符之间转换,就像调用mbrtowc和wcrtomb 一样。与在程序中有效的多字节字符串不同,文件中的多字节字符序列可能包含嵌入的空值,并且不必以初始移位状态开始或结束。
因此,一旦您使用printf()
了方向,您的方向就会变得狭窄,从这一点开始,您将无法从中获得任何东西,wprintf()
而您实际上也没有。除非您使用freeopen()
which 旨在用于文件。
答案 B
事实证明,您可以freeopen()
像这样使用:
freopen(NULL, "w", stdout);
再次使流“未定义”。试试这个例子:
#include <stdio.h>
#include <wchar.h>
#include <locale.h>
int main(void)
{
// We set locale which is the same as the enviromental variable "LANG=en_US.UTF-8".
setlocale(LC_ALL, "en_US.UTF-8");
// We define array of wide characters. We indicate this on both sides of equal sign
// with "wchar_t" on the left and "L" on the right.
wchar_t y[100] = L"€ο Δικαιοπολις εν αγρω εστιν\n";
// We print header in ASCII characters
wprintf(L"content-type:text/html; charset:utf-8\n\n");
// A newly opened stream has no orientation. The first call to any I/O function
// establishes the orientation: a wide I/O function makes the stream wide-oriented,
// a narrow I/O function makes the stream narrow-oriented. Once set, we must respect
// this, so for the time being we are stuck with either printf() or wprintf().
wprintf(L"%S\n", y); // Conversion specifier %S is not standardized (!)
wprintf(L"%ls\n", y); // Conversion specifier %s with length modifier %l is
// standardized (!)
// At this point curent orientation of the stream is wide and this is why folowing
// narrow function won't print anything! Whether we should use wprintf() or printf()
// is primarily a question of how we want output to be encoded.
printf("1\n"); // Print narrow string of characters with a narrow function
printf("%s\n", "2"); // Print narrow string of characters with a narrow function
printf("%ls\n",L"3"); // Print wide string of characters with a narrow function
// Now we reset the stream to no orientation.
freopen(NULL, "w", stdout);
printf("4\n"); // Print narrow string of characters with a narrow function
printf("%s\n", "5"); // Print narrow string of characters with a narrow function
printf("%ls\n",L"6"); // Print wide string of characters with a narrow function
return 0;
}