如何在C中设置运行时字符集? [英] How to set run-time character set in C?
问题描述
如何在Linux环境中使用C编程语言设置运行时字符集?
How to set run-time character set in the C programming language, in linux environment?
例如,我要将其设置为iso8859-1,utf -8或ascii。
For example, I want to set it to iso8859-1, utf-8, or ascii.
推荐答案
您需要更加清楚自己的意思。在大多数情况下,C并没有真正的字符集。它的字符串只是用空分隔的字节字符串,不做任何编码或解码。
You need to be a little more specific about what you mean. For the most part, C doesn't really have a character set; its strings are simply null-delimited strings of bytes, and doesn't do anything to encode or decode them.
C标准库中有一些函数,并且在POSIX中取决于当前语言环境。您可以使用use setlocale
设置当前语言环境;它默认为C语言环境,在该语言环境中,字符串被视为ASCII并根据字节值进行比较。
There are a few functions in the C standard library, and in POSIX which depend on the current locale. You can use use setlocale
to set the current locale; it defaults to the C locale, in which strings are treated as ASCII and compared according to byte values.
如果要转换字符集,请使用 iconv
;这将允许您将缓冲区从一种编码转换为另一种编码。例如,如果您在内部以UTF-8表示文本,但想在ISO-8859-1中打印出来,则将使用此文本。
If you want to convert character sets, use iconv
; this will allow you to convert buffers from one encoding to another. For instance, if you represent your text internally in UTF-8, but want to print it out in ISO-8859-1, this is what you would use.
要添加的编辑:从对另一个答案的评论中,您会询问:
edit to add: From a comment on another answer, you ask:
我将终端的预期字符集设置为是 ISO 8859-1,但是为什么当我调用函数
setlocale(LC_CTYPE,NULL);
时,它仍然返回C
?我认为它应该返回ISO 8859-1
,因为这是终端的预期字符集。
I set my terminal's expected character set to be "ISO 8859-1", but why when I call the function
setlocale( LC_CTYPE, NULL );
, it still returnsC
? I think it should returnISO 8859-1
as this is the terminal's expected charset.
程序启动时,其语言环境始终为 C。如果要基于环境变量设置语言环境,则需要调用 setlocale(LC_ALL,)
或 setlocal(LC_CTYPE, )
;也就是说,您需要传入一个空字符串,然后将根据您的环境变量设置语言环境。
When the program starts up, its locale is always "C". If you want to set the locale based on the environment variables, you need to call setlocale( LC_ALL, "")
or setlocal( LC_CTYPE, "")
; that is, you need to pass in an empty string, and then the locale will be set based on your environment variables.
这篇关于如何在C中设置运行时字符集?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!