gpt4 book ai didi

c - 在 glib 中打印 utf8

转载 作者:太空狗 更新时间:2023-10-29 17:20:15 24 4
gpt4 key购买 nike

为什么 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.

关于c - 在 glib 中打印 utf8,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3092354/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com