使用非ASCII字符进行fwrite [英] fwrite with non ASCII characters

查看:110
本文介绍了使用非ASCII字符进行fwrite的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑以下程序:

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

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

在Windows上,我得到以下输出:

On Windows I get the following output:

��

我尝试将行更改为此:

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

如何使用以非ASCII作为第一个字符的fwrite?

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

要回应一些评论:源文件已正确设置为UTF-8格式,我的代码页也已正确设置为UTF-8:

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

推荐答案

在Windows上,fwrite在内部调用WriteFile,在这种情况下是错误的.我的 解决方案是直接调用WriteFile:

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;
}

  • C运行时函数的Win32等效项
  • WriteFile函数
    • Win32 Equivalents for C Run-Time Functions
    • WriteFile function
    • 这篇关于使用非ASCII字符进行fwrite的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆