处理 C 中的特殊字符(UTF-8 编码) [英] Handling special characters in C (UTF-8 encoding)
问题描述
我正在用 C 编写一个小应用程序,它读取一个简单的文本文件,然后逐行输出.问题在于文本文件包含特殊字符,如 Æ、Ø 和 Å 等.当我在终端中运行程序时,这些字符的输出用?"表示.
I'm writing a small application in C that reads a simple text file and then outputs the lines one by one. The problem is that the text file contains special characters like Æ, Ø and Å among others. When I run the program in terminal the output for those characters are represented with a "?".
有没有简单的解决方法?
Is there an easy fix?
推荐答案
第一件事:
- 读入缓冲区
- 使用 libiconv 或类似工具从 UTF-8 中获取 wchar_t 类型并使用宽字符处理函数,例如 wprintf()
- 在 C 中使用宽字符函数!大多数文件/输出处理函数都有一个宽字符变体
确保您的终端可以处理 UTF-8 输出.拥有正确的语言环境设置和操作语言环境数据可以自动为您打开和转换大量文件……这取决于您在做什么.
Ensure that your terminal can handle UTF-8 output. Having the correct locale setup and manipulating the locale data can automate alot of the file opening and conversion for you ... depending on what you are doing.
记住,UTF-8 中代码点或字符的宽度是可变的.这意味着您不能只寻找一个字节并像使用 ASCII 一样开始读取……因为您可能会落在代码点的中间.在某些情况下,好的图书馆可以做到这一点.
Remember that the width of a code-point or character in UTF-8 is variable. This means you can't just seek to a byte and begin reading like with ASCII ... because you might land in the middle of a code point. Good libraries can do this in some cases.
这是一些代码(不是我的),它演示了在 C 中读取 UTF-8 文件和宽字符处理的一些用法.
Here is some code (not mine) that demonstrates some usage of UTF-8 file reading and wide character handling in C.
#include <stdio.h>
#include <wchar.h>
int main()
{
FILE *f = fopen("data.txt", "r, ccs=UTF-8");
if (!f)
return 1;
for (wint_t c; (c = fgetwc(f)) != WEOF;)
printf("%04X
", c);
fclose(f);
return 0;
}
链接
这篇关于处理 C 中的特殊字符(UTF-8 编码)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!