setlocale, _wsetlocalesetlocale, _wsetlocale

设置或检索运行时区域设置。Sets or retrieves the run-time locale.

语法Syntax

char *setlocale(
   int category,
   const char *locale
);
wchar_t *_wsetlocale(
   int category,
   const wchar_t *locale
);

参数Parameters

类别category
受区域设置影响的分类。Category affected by locale.

本地locale
区域设置说明符。Locale specifier.

返回值Return value

如果提供了有效的区域设置类别,则返回指向与指定的区域设置类别关联的字符串的指针。If a valid locale and category are given, returns a pointer to the string associated with the specified locale and category. 如果区域设置类别无效,则返回空指针,并且不更改程序的当前区域设置。If the locale or category isn't valid, returns a null pointer, and the current locale settings of the program are unchanged.

例如,调用For example, the call

setlocale( LC_ALL, "en-US" );

设置所有类别,只返回该字符串sets all categories, returning only the string

en-US

你可以复制由 setlocale 返回的字符串以还原程序的区域设置信息的该部分。You can copy the string returned by setlocale to restore that part of the program's locale information. 全局或线程本地存储用于由 setlocale 返回的字符串。Global or thread local storage is used for the string returned by setlocale. 稍后调用 setlocale 将覆盖字符串,这将使之前调用返回的字符串指针无效。Later calls to setlocale overwrite the string, which invalidates string pointers returned by earlier calls.

备注Remarks

使用 setlocale 函数设置、更改或查询由区域设置类别指定的某些或全部当前程序区域设置信息。Use the setlocale function to set, change, or query some or all of the current program locale information specified by locale and category. 区域设置是指可以为其自定义程序的某些方面的区域 (国家/地区和语言) 。locale refers to the locality (country/region and language) for which you can customize certain aspects of your program. 一些与区域设置相关的类别包括日期的格式设置和货币值的显示格式。Some locale-dependent categories include the formatting of dates and the display format for monetary values. 如果将 "区域设置" 设置为在计算机上支持多个窗体的语言的默认字符串,则应检查 setlocale 返回值以查看哪种语言有效。If you set locale to the default string for a language that has multiple forms supported on your computer, you should check the setlocale return value to see which language is in effect. 例如,如果将 "区域设置" 设置为 "中文",则返回值可能是 "简体中文" 或 "繁体中文"。For example, if you set locale to "chinese" the return value could be either "chinese-simplified" or "chinese-traditional".

_wsetlocale是的宽字符版本; 的 setlocale 区域设置参数和的返回值 _wsetlocale 都是宽字符字符串。_wsetlocale is a wide-character version of setlocale; the locale argument and return value of _wsetlocale are wide-character strings. 除此以外,_wsetlocalesetlocale 的行为完全相同。_wsetlocale and setlocale behave identically otherwise.

默认情况下,此函数的全局状态的作用域限定为应用程序。By default, this function's global state is scoped to the application. 若要更改此项,请参阅CRT 中的全局状态To change this, see Global state in the CRT.

一般文本例程映射Generic-Text Routine Mappings

TCHAR.H 例程TCHAR.H routine 未定义 _UNICODE 和 _MBCS_UNICODE & _MBCS not defined 已定义 _MBCS_MBCS defined 已定义 _UNICODE_UNICODE defined
_tsetlocale setlocale setlocale _wsetlocale

Category参数指定程序的受影响的部分区域设置信息。The category argument specifies the parts of a program's locale information that are affected. 用于类别的宏及其影响的程序的部分如下所示:The macros used for category and the parts of the program they affect are as follows:

类别标志category flag 影响Affects
LC_ALL 以下列出了所有类别。All categories, as listed below.
LC_COLLATE strcoll_stricollwcscoll_wcsicollstrxfrm_strncoll_strnicoll_wcsncoll_wcsnicollwcsxfrm 函数。The strcoll, _stricoll, wcscoll, _wcsicoll, strxfrm, _strncoll, _strnicoll, _wcsncoll, _wcsnicoll, and wcsxfrm functions.
LC_CTYPE 字符处理函数(不受影响的 isdigitisxdigitmbstowcsmbtowc 除外)。The character-handling functions (except isdigit, isxdigit, mbstowcs, and mbtowc, which are unaffected).
LC_MONETARY localeconv 函数返回的货币格式信息。Monetary-formatting information returned by the localeconv function.
LC_NUMERIC 格式化输出例程(例如 printf)、数据转换例程和 localeconv 所返回的非货币格式设置信息的十进制点字符。Decimal-point character for the formatted output routines (such as printf), for the data-conversion routines, and for the non-monetary formatting information returned by localeconv. 除小数点字符之外,LC_NUMERIC 还设置 localeconv 返回的千位分隔符和分组控制字符串。In addition to the decimal-point character, LC_NUMERIC sets the thousands separator and the grouping control string returned by localeconv.
LC_TIME strftimewcsftime 函数。The strftime and wcsftime functions.

此函数验证类别参数。This function validates the category parameter. 如果类别参数不是上表中提供的值之一,则会调用无效参数处理程序,如参数验证中所述。If the category parameter isn't one of the values given in the previous table, the invalid parameter handler is invoked, as described in Parameter Validation. 如果允许执行继续,则该函数将 errno 设置为 EINVAL 并返回 NULLIf execution is allowed to continue, the function sets errno to EINVAL and returns NULL.

Locale参数是指向指定区域设置的字符串的指针。The locale argument is a pointer to a string that specifies the locale. 有关区域设置参数格式的信息,请参阅区域设置名称、语言和国家/地区字符串For information about the format of the locale argument, see Locale Names, Languages, and Country/Region Strings. 如果 locale 指向一个空字符串,则区域设置是实现定义的本机环境。If locale points to an empty string, the locale is the implementation-defined native environment. C 的值为 C 转换指定最小的符合 ANSI 标准的环境。A value of C specifies the minimal ANSI conforming environment for C translation. C 区域设置假设所有 char 数据类型为 1 字节,并且其值始终小于 256。The C locale assumes that all char data types are 1 byte and that their value is always less than 256.

在程序启动时,将执行以下语句的等效项:At program startup, the equivalent of the following statement is executed:

setlocale( LC_ALL, "C" );

区域设置参数可以采用区域设置名称、语言字符串、语言字符串和国家/地区代码、代码页或语言字符串、国家/地区代码和代码页。The locale argument can take a locale name, a language string, a language string and country/region code, a code page, or a language string, country/region code, and code page. 可用区域设置名称、语言、国家/地区代码和代码页集包含 Windows NLS API 支持的所有功能。The set of available locale names, languages, country/region codes, and code pages includes all those supported by the Windows NLS API. 区域设置名称、语言和国家/地区字符串中介绍了 setlocale 所支持的区域设置名称集合。The set of locale names supported by setlocale are described in Locale Names, Languages, and Country/Region Strings. 语言字符串国家/地区字符串中列出了 setlocale 所支持的语言和国家/地区字符串集合。The set of language and country/region strings supported by setlocale are listed in Language Strings and Country/Region Strings. 建议对嵌入到代码中或序列化到存储中的区域设置字符串的性能和可维护性使用区域设置名称格式。We recommend the locale name form for performance and for maintainability of locale strings embedded in code or serialized to storage. 与语言和国家/地区名称格式相比,操作系统的更新更改区域设置名称字符串的可能性会小一些。The locale name strings are less likely to be changed by an operating system update than the language and country/region name form.

作为区域设置参数传递的 null 指针告知 setlocale 查询而不是设置国际环境。A null pointer that's passed as the locale argument tells setlocale to query instead of to set the international environment. 如果locale参数为 null 指针,则不更改程序的当前区域设置。If the locale argument is a null pointer, the program's current locale setting isn't changed. 相反, setlocale 返回指向与线程的当前区域设置的类别关联的字符串的指针。Instead, setlocale returns a pointer to the string that's associated with the category of the thread's current locale. 如果category参数为 LC_ALL ,则该函数将返回一个字符串,该字符串指示每个类别的当前设置(用分号分隔)。If the category argument is LC_ALL, the function returns a string that indicates the current setting of each category, separated by semicolons. 例如,调用的顺序For example, the sequence of calls

// Set all categories and return "en-US"
setlocale(LC_ALL, "en-US");
// Set only the LC_MONETARY category and return "fr-FR"
setlocale(LC_MONETARY, "fr-FR");
printf("%s\n", setlocale(LC_ALL, NULL));

返回returns

LC_COLLATE=en-US;LC_CTYPE=en-US;LC_MONETARY=fr-FR;LC_NUMERIC=en-US;LC_TIME=en-US

它是与 LC_ALL 类别关联的字符串。which is the string that's associated with the LC_ALL category.

以下示例与 LC_ALL 类别相关。The following examples pertain to the LC_ALL category. 字符串 "。OCP "and"。可以使用 ACP "而不是代码页号来指定用户默认的 OEM 代码页和该区域设置名称的用户默认的 ANSI 代码页。Either of the strings ".OCP" and ".ACP" can be used instead of a code page number to specify use of the user-default OEM code page and user-default ANSI code page for that locale name, respectively.

  • setlocale( LC_ALL, "" );

    将区域设置设定为默认值,该值是从操作系统获得的用户默认的 ANSI 代码页。Sets the locale to the default, which is the user-default ANSI code page obtained from the operating system. 区域设置名称设置为GetUserDefaultLocaleName返回的值。The locale name is set to the value returned by GetUserDefaultLocaleName. 将代码页设置为GetACP返回的值。The code page is set to the value returned by GetACP.

  • setlocale( LC_ALL, ".OCP" );

    将区域设置设置为从操作系统获得的当前 OEM 代码页。Sets the locale to the current OEM code page obtained from the operating system. 区域设置名称设置为GetUserDefaultLocaleName返回的值。The locale name is set to the value returned by GetUserDefaultLocaleName. 通过GetLocaleInfoEx将代码页设置为用户默认区域设置名称的LOCALE_IDEFAULTCODEPAGE值。The code page is set to the LOCALE_IDEFAULTCODEPAGE value for the user-default locale name by GetLocaleInfoEx.

  • setlocale( LC_ALL, ".ACP" );

    将区域设置设定为从操作系统获得的 ANSI 代码页。Sets the locale to the ANSI code page obtained from the operating system. 区域设置名称设置为GetUserDefaultLocaleName返回的值。The locale name is set to the value returned by GetUserDefaultLocaleName. 通过GetLocaleInfoEx将代码页设置为用户默认区域设置名称的LOCALE_IDEFAULTANSICODEPAGE值。The code page is set to the LOCALE_IDEFAULTANSICODEPAGE value for the user-default locale name by GetLocaleInfoEx.

  • setlocale( LC_ALL, "<localename>" );

    将区域设置设置为指示的区域设置名称 <localename>Sets the locale to the locale name that's indicated by <localename>. 通过GetLocaleInfoEx将代码页设置为指定的区域设置名称的LOCALE_IDEFAULTANSICODEPAGE值。The code page is set to the LOCALE_IDEFAULTANSICODEPAGE value for the specified locale name by GetLocaleInfoEx.

  • setlocale( LC_ALL, "<language>_<country>" );

    将区域设置设置为所指示的语言和国家/ <language> 地区 <country> ,以及从主机操作系统获得的默认代码页。Sets the locale to the language and country/region indicated by <language> and <country>, together with the default code page obtained from the host operating system. 通过GetLocaleInfoEx将代码页设置为指定的区域设置名称的LOCALE_IDEFAULTANSICODEPAGE值。The code page is set to the LOCALE_IDEFAULTANSICODEPAGE value for the specified locale name by GetLocaleInfoEx.

  • setlocale( LC_ALL, "<language>_<country>.<code_page>" );

    将区域设置设置为 <language> 、和字符串指示的语言、国家/地区和代码页 <country> <code_page>Sets the locale to the language, country/region, and code page indicated by the <language>, <country>, and <code_page> strings. 你可以使用语言、国家/地区和代码页的各种组合。You can use various combinations of language, country/region, and code page. 例如,此调用会将区域设置设定为“法语(加拿大)”并使用代码页 1252:For example, this call sets the locale to French Canada with code page 1252:

    setlocale( LC_ALL, "French_Canada.1252" );

    此调用会将区域设置设定为“法语(加拿大)”并使用默认 ANSI 代码页:This call sets the locale to French Canada with the default ANSI code page:

    setlocale( LC_ALL, "French_Canada.ACP" );

    此调用会将区域设置设定为“法语(加拿大)”并使用默认 OEM 代码页:This call sets the locale to French Canada with the default OEM code page:

    setlocale( LC_ALL, "French_Canada.OCP" );

  • setlocale( LC_ALL, "<language>" );

    将区域设置设置为所指示的语言 <language> ,并为指定的语言使用默认国家/地区,并为该国家/地区使用从主机操作系统获得的用户默认的 ANSI 代码页。Sets the locale to the language that's indicated by <language>, and uses the default country/region for the specified language and the user-default ANSI code page for that country/region as obtained from the host operating system. 例如,以下对 setlocale 的调用在功能上是等效的:For example, the following calls to setlocale are functionally equivalent:

    setlocale( LC_ALL, "en-US" );

    setlocale( LC_ALL, "English" );

    setlocale( LC_ALL, "English_United States.1252" );

    建议使用第一种形式以实现较高的性能和可维护性。We recommend the first form for performance and maintainability.

  • setlocale( LC_ALL, ".<code_page>" );

    将代码页设置为由 <code_page> 指示的值,以及指定代码页的默认国家/地区和语言(由主机操作系统定义)。Sets the code page to the value indicated by <code_page>, together with the default country/region and language (as defined by the host operating system) for the specified code page.

类别必须是 LC_ALLLC_CTYPE 才能影响代码页的更改。The category must be either LC_ALL or LC_CTYPE to effect a change of code page. 例如,如果主机操作系统的默认国家/地区和语言为“美国”和“英语”,则以下两个对 setlocale 的调用在功能上是等效的:For example, if the default country/region and language of the host operating system are "United States" and "English," the following two calls to setlocale are functionally equivalent:

setlocale( LC_ALL, ".1252" );

setlocale( LC_ALL, "English_United States.1252");

有关详细信息,请参阅 setlocale C/c + + 预处理器参考中的杂注指令。For more information, see the setlocale pragma directive in the C/C++ Preprocessor Reference.

函数 _configthreadlocale 用于控制 setlocale 是否影响程序中所有线程的区域设置或仅影响调用线程的区域设置。The function _configthreadlocale is used to control whether setlocale affects the locale of all threads in a program or only the locale of the calling thread.

UTF-8 支持UTF-8 Support

从 Windows 10 build 17134 开始 (2018 年4月更新) ,通用 C 运行时支持使用 UTF-8 代码页。Starting in Windows 10 build 17134 (April 2018 Update), the Universal C Runtime supports using a UTF-8 code page. 这意味着 char 传递给 C 运行时函数的字符串将需要 utf-8 编码格式的字符串。This means that char strings passed to C runtime functions will expect strings in the UTF-8 encoding. 若要启用 UTF-8 模式,请在使用时使用 "UTF-8" 作为代码页 setlocaleTo enable UTF-8 mode, use "UTF-8" as the code page when using setlocale. 例如, setlocale(LC_ALL, ".utf8") 将使用当前默认 WINDOWS ANSI 代码页 (ACP) 用于区域设置,并使用 utf-8 作为代码页。For example, setlocale(LC_ALL, ".utf8") will use the current default Windows ANSI code page (ACP) for the locale and UTF-8 for the code page.

调用后 setlocale(LC_ALL, ".UTF8") ,你可以将 "" 传递给, 😊 mbtowcs 并将其正确地转换为 wchar_t 字符串,但之前没有可用于执行此操作的区域设置。After calling setlocale(LC_ALL, ".UTF8"), you may pass "😊" to mbtowcs and it will be properly translated to a wchar_t string, whereas previously there was not a locale setting available to do this.

对于 char 使用默认 WINDOWS ANSI 代码页( (ACP) )的已翻译字符串,也启用了 utf-8 模式。UTF-8 mode is also enabled for functions that have historically translated char strings using the default Windows ANSI code page (ACP). 例如, _mkdir("😊") 当使用 utf-8 代码页时,调用会正确生成包含该表情符号作为文件夹名称的目录,而不需要在运行程序之前将 ACP 更改为 utf-8。For example, calling _mkdir("😊") while using a UTF-8 code page will correctly produce a directory with that emoji as the folder name, instead of requiring the ACP to be changed to UTF-8 prior to running your program. 同样, _getcwd() 在该文件夹内调用将返回 utf-8 编码的字符串。Likewise, calling _getcwd() inside of that folder will return a UTF-8 encoded string. 为实现兼容性,如果 C 区域设置代码页未设置为 UTF-8,则仍将使用 ACP。For compatibility, the ACP is still used if the C locale code page is not set to UTF-8.

C 运行时的以下方面不能使用 utf-8,因为在程序启动过程中设置了 utf-8,并且必须使用默认的 Windows ANSI 代码页 (ACP) : __argv_acmdln_pgmptrThe following aspects of the C Runtime that are not able to use UTF-8 because they are set during program startup and must use the default Windows ANSI code page (ACP): __argv, _acmdln, and _pgmptr.

之前,此支持、 mbrtoc16 mbrtoc32 c16rtomb c32rtomb存在于 utf-8 窄字符串之间,utf-16 (与 wchar_t Windows 平台上的相同编码) 和32。Previous to this support, mbrtoc16, mbrtoc32, c16rtomb, and c32rtomb existed to translate between UTF-8 narrow strings, UTF-16 (same encoding as wchar_t on Windows platforms) and UTF-32. 出于兼容性原因,这些 Api 仍只能从 utf-8 转换到 utf-8,而不是通过设置代码页 setlocaleFor compatibility reasons, these APIs still only translate to and from UTF-8 and not the code page set via setlocale.

若要在 Windows 10 之前的操作系统(如 Windows 7)上使用此功能,必须使用 Windows SDK 或更高版本的17134版的应用程序本地部署或静态链接。To use this feature on an OS prior to Windows 10, such as Windows 7, you must use app-local deployment or link statically using version 17134 of the Windows SDK or later. 对于17134之前的 Windows 10 操作系统,仅支持静态链接。For Windows 10 operating systems prior to 17134, only static linking is supported.

要求Requirements

例程所返回的值Routine 必需的标头Required header
setlocale <locale.h>
_wsetlocale <locale.h> 或 <wchar.h><locale.h> or <wchar.h>

有关其他兼容性信息,请参阅兼容性For additional compatibility information, see Compatibility.

示例Example

// crt_setlocale.c
//
// This program demonstrates the use of setlocale when
// using two independent threads.
//

#include <locale.h>
#include <process.h>
#include <windows.h>
#include <stdio.h>
#include <time.h>

#define BUFF_SIZE 100

// Retrieve the date in the current
// locale's format.
int get_date(unsigned char* str)
{
    __time64_t ltime;
    struct tm  thetime;

    // Retrieve the current time
    _time64(&ltime);
    _gmtime64_s(&thetime, &ltime);

    // Format the current time structure into a string
    // "%#x" is the long date representation in the
    // current locale
    if (!strftime((char *)str, BUFF_SIZE, "%#x",
                  (const struct tm *)&thetime))
    {
        printf("strftime failed!\n");
        return -1;
    }
    return 0;
}

// This thread sets its locale to the argument
// and prints the date.
uintptr_t __stdcall SecondThreadFunc( void* pArguments )
{
    unsigned char str[BUFF_SIZE];
    char * locale = (char *)pArguments;

    // Set the thread locale
    printf("The thread locale is now set to %s.\n",
           setlocale(LC_ALL, locale));

    // Retrieve the date string from the helper function
    if (get_date(str) == 0)
    {
        printf("The date in %s locale is: '%s'\n", locale, str);
    }

    _endthreadex( 0 );
    return 0;
}

// The main thread sets the locale to English
// and then spawns a second thread (above) and prints the date.
int main()
{
    HANDLE          hThread;
    unsigned        threadID;
    unsigned char   str[BUFF_SIZE];

    // Enable per-thread locale causes all subsequent locale
    // setting changes in this thread to only affect this thread.
    _configthreadlocale(_ENABLE_PER_THREAD_LOCALE);

    // Set the locale of the main thread to US English.
    printf("The thread locale is now set to %s.\n",
           setlocale(LC_ALL, "en-US"));

    // Create the second thread with a German locale.
    // Our thread function takes an argument of the locale to use.
    hThread = (HANDLE)_beginthreadex( NULL, 0, &SecondThreadFunc,
                                      "de-DE", 0, &threadID );

    if (get_date(str) == 0)
    {
        // Retrieve the date string from the helper function
        printf("The date in en-US locale is: '%s'\n\n", str);
    }

    // Wait for the created thread to finish.
    WaitForSingleObject( hThread, INFINITE );

    // Destroy the thread object.
    CloseHandle( hThread );
}
The thread locale is now set to en-US.
The time in en-US locale is: 'Wednesday, May 12, 2004'

The thread locale is now set to de-DE.
The time in de-DE locale is: 'Mittwoch, 12. Mai 2004'

另请参阅See also

区域设置名称、语言和国家/地区字符串Locale Names, Languages, and Country/Region Strings
_configthreadlocale_configthreadlocale
_create_locale,_wcreate_locale_create_locale, _wcreate_locale
本地Locale
localeconvlocaleconv
_mbclen、mblen、_mblen_l_mbclen, mblen, _mblen_l
strlen、wcslen、_mbslen、_mbslen_l、_mbstrlen _mbstrlen_lstrlen, wcslen, _mbslen, _mbslen_l, _mbstrlen, _mbstrlen_l
mbstowcs、_mbstowcs_lmbstowcs, _mbstowcs_l
mbtowc、_mbtowc_lmbtowc, _mbtowc_l
_setmbcp_setmbcp
strcoll 函数strcoll Functions
strftime、wcsftime、_strftime_l、_wcsftime_lstrftime, wcsftime, _strftime_l, _wcsftime_l
strxfrm、wcsxfrm、_strxfrm_l、_wcsxfrm_lstrxfrm, wcsxfrm, _strxfrm_l, _wcsxfrm_l
wcstombs、_wcstombs_lwcstombs, _wcstombs_l
wctomb、_wctomb_lwctomb, _wctomb_l