fwrite with non ASCII characters

眉间皱痕 提交于 2019-12-08 05:00:43

问题


Consider the following program:

#include <stdio.h>
#include <string.h>

int main() {
  char* alpha = "Ω";
  fwrite(alpha, 1, strlen(alpha), stdout);
  return 0;
}

On Windows I get the following output:

��

I tried changing the line to this:

char* alpha = "zΩ";

and it prints correctly. The output is encoded correctly, just not printing correctly:

$ bad | od -tx1c
0000000  ce  a9
        316 251

$ good | od -tx1c
0000000  7a  ce  a9
          z 316 251

How can I use fwrite with non ASCII as the first character?

To response to some comments: The source file is correctly formatted as UTF-8, and my code page is also correctly set as UTF-8:

$ chcp.com
Active code page: 65001

回答1:


On Windows fwrite calls WriteFile internally, in this case incorrectly. My solution was to just call WriteFile directly:

#include <windows.h>

int main() {
  char* alpha = "Ω";
  DWORD bravo;
  WriteFile(GetStdHandle(STD_OUTPUT_HANDLE), alpha, strlen(alpha), &bravo, 0);
  return 0;
}
  • Win32 Equivalents for C Run-Time Functions
  • WriteFile function


来源:https://stackoverflow.com/questions/30961728/fwrite-with-non-ascii-characters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!