Setlocale c что это

от admin

Функция setlocale

Функция setlocale задает локаль, которая будет использоваться текущей программой. Можно изменить все параметры локали, или конкретные её части. Эта функция также может быть использована для получения имени текущей локали, передав NULL в через параметр locale .

Локаль содержит информацию о том, как интерпретировать и выполнять определенные операции ввода/вывода и преобразования с учетом географического расположения и специфики языков в определённых условиях.

Большинство используемых сред программирования имеют определенную информацию о локали, установленной в соответствии с предпочтениями пользователя или автоматической локализации. Но, независимо от этой системной локали, в момент запуска, все Си-программы имеют установленную Cи -локаль, которая является нейтральной локалью с минимальной информацией, что позволяет предсказать результат программы. Для того чтобы использовать, по умолчанию, локаль установленную в среде программирования, необходимо вызвать функцию setlocale с параметром locale равным «» .

По умолчанию, установлена локаль: SetLocale (LC_ALL, «C») .
Вся локаль, по умолчанию, может быть установлена вызовом функции SetLocale (LC_ALL, «»);
Если необходимо изменить часть текущей локали, вместо параметра LC_ALL определяем параметр определённой категории. Какие именно категории есть, вы можете увидеть в таблице, ниже.

Чтобы изменить все параметры локали, необходимо вызвать функцию setlocale с параметром category LC_ALL , на пример, так: setlocale(LC_ALL,"");

Конкретные параметры текущей локали зависят от вызова функции setlocale , предварительно указав параметр category .

Параметры:

  • category
    Параметры локали, можно задавать отдельно каждый параметр или все сразу. В заголовочном файле<clocale> определены константы, содержащие значения для этого параметра:
  • locale
    Строка, содержащая имя локали. Как минимум существуют два значения, передаваемые через этот параметр:

Если значение этого параметра равно NULL , функция не вносит никаких изменений в текущую локаль, но имя текущей локали возвращается функцией.

Возвращаемое значение

В случае успеха, функция возвращает указатель на строку с установленной локалью для данной категории.

Если установлена категория LC_ALL и для различных частей локали установлены различные значения, возвращаемая строка предоставляет эту информацию в формате, который может варьироваться от реализации компилятора.

Если функции не удалось установить новую локаль, текущая локаль остается неизменной и возвращается нулевой указатель.

setlocale

Sets locale information to be used by the current program, either changing the entire locale or portions of it. The function can also be used to retrieve the current locale’s name by passing NULL as the value for argument locale .

Locales contain information on how to interpret and perform certain input/output and transformation operations taking into consideration location and language specific settings.

Most running environments have certain locale information set according to the user preferences or localization. But, independently of this system locale, on start, all C programs have the «C» locale set, which is a rather neutral locale with minimal locale information that allows the result of programs to be predictable. In order to use the default locale set in the environment, this function can be called with «» as argument locale .

On program startup, the locale selected is the «C» locale , which is the same as would be set by calling setlocale(LC_ALL,»C») .

The locale settings selected in the environment can be selected by calling setlocale(LC_ALL,»») .

The portions of the current locale affected by a call to this function are specified by argument category .

Parameters

category Portion of the locale affected. It is one of the following constant values defined as macros in <clocale> :

value Portion of the locale affected
LC_ALL The entire locale.
LC_COLLATE Affects the behavior of strcoll and strxfrm .
LC_CTYPE Affects character handling functions (all functions of <cctype> , except isdigit and isxdigit ), and the multibyte and wide character functions.
LC_MONETARY Affects monetary formatting information returned by localeconv .
LC_NUMERIC Affects the decimal-point character in formatted input/output operations and string formatting functions, as well as non-monetary information returned by localeconv .
LC_TIME Affects the behavior of strftime .

locale C string containing the name of a C locale. These are system specific, but at least the two following locales must exist:

locale name description
«C» Minimal «C» locale
«» Environment’s default locale

If the value of this parameter is NULL , the function does not make any changes to the current locale, but the name of the current locale is still returned by the function.

Return Value

On success, A pointer to a C string identifying the locale currently set for the category . If category is LC_ALL and different portions of the locale are set to different values, the string returned gives this information in a format which may vary between library implementations.

If the function failed to set a new locale, this is not modified and a null pointer is returned.

Setlocale c что это

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

ОПИСАНИЕ

Если locale не равно NULL, то текущая локаль программы изменяется согласно переданным аргументам. Аргументом category определяется какую часть текущей локали программы нужно изменить.

Категория Определяет
LC_ALL Локаль целиком
LC_ADDRESS Форматирование адресов и
элементов, относящихся к географии (*)
LC_COLLATE Сортировка строк
LC_CTYPE Классы символов
LC_IDENTIFICATION Метаданные, описывающие локаль (*)
LC_MEASUREMENT Настройки, относящиеся к единицам измерения
(метрические или системы мер США) (*)
LC_MESSAGES Локализированные сообщения на родном языке
LC_MONETARY Форматирование значений денежных единиц
LC_NAME Форматирование приветствий людей (*)
LC_NUMERIC Форматирование неденежных числовых значений
LC_PAPER Настройки стандартных размеров бумаги (*)
LC_TELEPHONE Форматы, используемые в телефонных службах (*)
LC_TIME Форматирование значений дат и времени

Категории, помеченные в таблице звёздочкой, являются расширениями GNU. Дополнительную информацию об этих категориях локали смотрите в locale(7).

Аргумент locale — это указатель на строку символов, содержащую требуемую настройку category. Эта строка может быть понятной константой «C» или «da_DK» (смотрите ниже), или неясной строкой, которую вернул другой вызов setlocale().

Если locale — пустая строка, «», то любая часть локали, которую требуется изменить, будет задана исходя из переменных окружения. Как это происходит — зависит от реализации. В glibc, во-первых (независимо от category), просматривается переменная окружения LC_ALL, затем переменная окружения с именем как у категории (смотрите таблицу выше), и в конце учитывается переменная окружения LANG. Используется первая найденная переменная окружения. Если её значение некорректно определяет локаль, то локаль не изменяется и setlocale() возвращает NULL.

Локали «C» или «POSIX» являются переносимыми локалями; они существуют во всех соответствующих системах.

Имя локали, обычно, состоит из языка[_территории][.таблицы символов][@модификатора], где язык — код языка согласно ISO 639, территория — код страны согласно ISO 3166 и таблица символов — набор символов или кодировка типа ISO-8859-1 или UTF-8. Список поддерживаемых локалей можно получить по команде «locale -a», смотрите locale(1).

Если locale равно NULL, то только возвращается текущая локаль и ничего не меняется.

При запуске основной программы по умолчанию выбирается переносимая локаль «C». Программу можно сделать переносимой для всех локалей вызвав

после инициализации программы, используя информацию об установках локали, полученную из вызова localeconv(3), используя многобайтные или широкосимвольные функции при обработке текста, если MB_CUR_MAX > 1 и используя strcoll(3), wcscoll(3) или strxfrm(3), wcsxfrm(3) для сравнения строк.

Name already in use

cpp-docs / docs / c-runtime-library / reference / setlocale-wsetlocale.md

  • Go to file T
  • Go to line L
  • Copy path
  • Copy permalink
  • Open with Desktop
  • View raw
  • Copy raw contents Copy raw contents

Copy raw contents

Copy raw contents

Sets or retrieves the run-time locale.

category
Category affected by locale.

locale
Locale specifier.

If a valid locale and category are given, the functions return a pointer to the string associated with the specified locale and category .

If the locale or category isn’t valid, the invalid parameter handler is invoked, as described in Parameter validation. If execution is allowed to continue, each function sets errno to EINVAL , and returns NULL .

sets all categories, returning only the string

You can copy the string returned by setlocale to restore that part of the program’s locale information. Global or thread local storage is used for the string returned by setlocale . Later calls to setlocale overwrite the string, which invalidates string pointers returned by earlier calls.

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. 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 is a wide-character version of setlocale ; the locale argument and return value of _wsetlocale are wide-character strings. _wsetlocale and setlocale behave identically otherwise.

By default, this function’s global state is scoped to the application. To change this behavior, see Global state in the CRT.

Generic-text routine mappings

TCHAR.H routine _UNICODE and _MBCS not defined _MBCS defined _UNICODE defined
_tsetlocale setlocale setlocale _wsetlocale

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 The strcoll , _stricoll , wcscoll , _wcsicoll , strxfrm , _strncoll , _strnicoll , _wcsncoll , _wcsnicoll , and wcsxfrm functions.
LC_CTYPE The character-handling functions (except isdigit , isxdigit , mbstowcs , and mbtowc , which are unaffected).
LC_MONETARY Monetary-formatting information returned by the localeconv function.
LC_NUMERIC 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 . In addition to the decimal-point character, LC_NUMERIC sets the thousands separator and the grouping control string returned by localeconv .
LC_TIME 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. If execution is allowed to continue, the function sets errno to EINVAL and returns NULL .

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. If locale points to an empty string, the locale is the implementation-defined native environment. A value of C specifies the minimal ANSI conforming environment for C translation. 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. The available locale names, languages, country/region codes, and code pages include all the ones supported by the Windows NLS API. The set of locale names supported by setlocale is described in Locale names, Languages, and Country/Region strings. 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.

A null pointer that’s passed as the locale argument tells setlocale to query instead of to set the international environment. If the locale argument is a null pointer, the program’s current locale setting isn’t changed. Instead, setlocale returns a pointer to the string that’s associated with the category of the thread’s current locale. 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

which is the string that’s associated with the LC_ALL category.

The following examples pertain to the LC_ALL category. 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.

Sets the locale to the default, which is the user-default ANSI code page obtained from the operating system. The locale name is set to the value returned by GetUserDefaultLocaleName . The code page is set to the value returned by GetACP .

setlocale( LC_ALL, «.OCP» );

Sets the locale to the current OEM code page obtained from the operating system. The locale name is set to the value returned by GetUserDefaultLocaleName . The code page is set to the LOCALE_IDEFAULTCODEPAGE value for the user-default locale name by GetLocaleInfoEx .

setlocale( LC_ALL, «.ACP» );

Sets the locale to the ANSI code page obtained from the operating system. The locale name is set to the value returned by GetUserDefaultLocaleName . The code page is set to the LOCALE_IDEFAULTANSICODEPAGE value for the user-default locale name by GetLocaleInfoEx .

setlocale( LC_ALL, «<localename>» );

Sets the locale to the locale name that’s indicated by <localename> . The code page is set to the LOCALE_IDEFAULTANSICODEPAGE value for the specified locale name by GetLocaleInfoEx .

setlocale( LC_ALL, «<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. The code page is set to the LOCALE_IDEFAULTANSICODEPAGE value for the specified locale name by GetLocaleInfoEx .

setlocale( LC_ALL, «<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. For example, this call sets the locale to French Canada with code page 1252:

setlocale( LC_ALL, «French_Canada.1252» );

This call sets the locale to French Canada with the default ANSI code page:

setlocale( LC_ALL, «French_Canada.ACP» );

This call sets the locale to French Canada with the default OEM code page:

setlocale( LC_ALL, «French_Canada.OCP» );

setlocale( LC_ALL, «<language>» );

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. 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>» );

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.

The category must be either LC_ALL or LC_CTYPE to effect a change of code page. 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»);

For more information, see the setlocale pragma directive in the C/C++ Preprocessor Reference.

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.

Starting in Windows 10 version 1803 (10.0.17134.0), the Universal C Runtime supports using a UTF-8 code page. The change means that char strings passed to C runtime functions can expect strings in the UTF-8 encoding. To enable UTF-8 mode, use «.UTF8» as the code page when using setlocale . 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.

The string to specify UTF-8 mode is:

  • case-insensitive
  • the hyphen ( — ) is optional
  • It must be in the code page part of the locale name, so must have a leading period ( . ) as in these examples: «en_US.UTF8» or «.utf8»

The following examples show how to specify the UTF-8 string:

After calling setlocale(LC_ALL, «.UTF8″) , you may pass » �� » to mbtowcs and it will be properly translated to a wchar_t string. Previously, there wasn’t a locale setting available to do this translation.

UTF-8 mode is also enabled for functions that have historically translated char strings using the default Windows ANSI code page (ACP). 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 before running your program. Likewise, calling _getcwd() in that folder will return a UTF-8 encoded string. For compatibility, the ACP is still used if the C locale code page isn’t set to UTF-8.

The following aspects of the C Runtime can’t use UTF-8 because they’re set during program startup and must use the default Windows ANSI code page (ACP): __argv , _acmdln , and _pgmptr .

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. For compatibility reasons, these APIs still only translate to and from UTF-8 and not the code page set via setlocale .

To use this feature on an OS prior to Windows 10, you must use app-local deployment or link statically using version 1803 (10.0.17134.0) of the Windows SDK or later. For Windows 10 operating systems prior to 1803 (10.0.17134.0), only static linking is supported.

Читать:
Как подняться на уровень выше в директории html

Похожие статьи