fwrite 非 ASCII 字符
fwrite with non ASCII characters
考虑以下程序:
#include <stdio.h>
#include <string.h>
int main() {
char* alpha = "Ω";
fwrite(alpha, 1, strlen(alpha), stdout);
return 0;
}
在 Windows 我得到以下输出:
��
我尝试将行更改为:
char* alpha = "zΩ";
并且打印正确。输出编码正确,只是不打印
正确:
$ bad | od -tx1c
0000000 ce a9
316 251
$ good | od -tx1c
0000000 7a ce a9
z 316 251
如何使用非 ASCII 作为第一个字符的 fwrite?
回复一些评论:源文件格式正确为UTF-8,我的代码页也正确设置为UTF-8:
$ chcp.com
Active code page: 65001
On Windows fwrite
在内部调用 WriteFile
,在本例中是错误的。我的
解决方案是直接调用 WriteFile
:
#include <windows.h>
int main() {
char* alpha = "Ω";
DWORD bravo;
WriteFile(GetStdHandle(STD_OUTPUT_HANDLE), alpha, strlen(alpha), &bravo, 0);
return 0;
}
考虑以下程序:
#include <stdio.h>
#include <string.h>
int main() {
char* alpha = "Ω";
fwrite(alpha, 1, strlen(alpha), stdout);
return 0;
}
在 Windows 我得到以下输出:
��
我尝试将行更改为:
char* alpha = "zΩ";
并且打印正确。输出编码正确,只是不打印 正确:
$ bad | od -tx1c 0000000 ce a9 316 251 $ good | od -tx1c 0000000 7a ce a9 z 316 251
如何使用非 ASCII 作为第一个字符的 fwrite?
回复一些评论:源文件格式正确为UTF-8,我的代码页也正确设置为UTF-8:
$ chcp.com Active code page: 65001
On Windows fwrite
在内部调用 WriteFile
,在本例中是错误的。我的
解决方案是直接调用 WriteFile
:
#include <windows.h>
int main() {
char* alpha = "Ω";
DWORD bravo;
WriteFile(GetStdHandle(STD_OUTPUT_HANDLE), alpha, strlen(alpha), &bravo, 0);
return 0;
}