c – 在glib中打印utf8

前端之家收集整理的这篇文章主要介绍了c – 在glib中打印utf8前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
为什么utf8符号无法通过glib函数打印?

代码

#include "glib.h"
#include <stdio.h>

int main() {
    g_print("марко\n");
    fprintf(stdout,"марко\n");
}

像这样构建:

gcc main.c -o main $(pkg-config glib-2.0 --cflags --libs)

你可以看到glib无法打印utf8和fprintf可以:

[marko@marko-work utf8test]$./main 
?????
марко

解决方法

fprint函数假定您使用它们打印的每个字符串都已正确编码,以匹配终端的当前编码. g_print()不会假设并且如果它认为有必要将转换编码;当然,这是一个坏主意,如果之前的编码实际上是正确的,因为这很可能会破坏编码.您的终端的区域设置是什么?

您可以在大多数系统上通过环境变量设置正确的区域设置,也可以使用setlocale函数以编程方式执行.区域设置名称是系统相关的(不是POSIX标准的一部分),但在大多数系统上,以下内容将起作用:

#include <locale.h>

:

setlocale(LC_ALL,"en_US.utf8");

除了LC_ALL之外,您还可以仅为某些操作设置区域设置(例如,“en_US”将导致英文编号和日期格式,但您可能不希望以这种方式格式化数字/日期).要引用setlocale手册页:

LC_ALL Set the entire locale
generically.

LC_COLLATE Set a locale for string
collation routines. This controls
alphabetic ordering in
strcoll() and strxfrm().

LC_CTYPE Set a locale for the
ctype(3) and multibyte(3) functions.
This controls recognition of
upper and lower case,alphabetic or non-alphabetic
characters,and so on.

LC_MESSAGES Set a locale for message
catalogs,see catopen(3) function.

LC_MONETARY Set a locale for
formatting monetary values; this
affects the localeconv() function.

LC_NUMERIC Set a locale for
formatting numbers. This controls the
formatting of decimal points in
input and output of floating point numbers in functions
such as printf() and scanf(),as
well as values returned by localeconv().

LC_TIME Set a locale for
formatting dates and times using the
strftime() function.

所有系统上始终可用的唯一两个区域设置值是“C”,“POSIX”和“”.

Only three locales are defined by default: the empty string “” (which denotes the native environment) and the “C” and “POSIX” locales (which denote the C-language environment). A locale argument of NULL causes setlocale() to return the current locale. By default,C programs start in the “C” locale. The only function in the library that sets the locale is setlocale(); the locale is never changed as a side effect of some other routine.

原文链接:https://www.f2er.com/c/239679.html

猜你在找的C&C++相关文章