Node:Setting the Locale, Next:Standard Locales, Previous:Locale Categories, Up:Locales
A C program inherits its locale environment variables when it starts up.
This happens automatically. However, these variables do not
automatically control the locale used by the library functions, because
ISO C says that all programs start by default in the standard C
locale. To use the locales specified by the environment, you must call
setlocale
. Call it as follows:
setlocale (LC_ALL, "");
to select a locale based on the user choice of the appropriate environment variables.
You can also use setlocale
to specify a particular locale, for
general use or for a specific category.
The symbols in this section are defined in the header file locale.h
.
char * setlocale (int category, const char *locale) | Function |
The function setlocale sets the current locale for category
category to locale. A list of all the locales the system
provides can be created by running
locale -a If category is You can also use this function to find out the current locale by passing
a null pointer as the locale argument. In this case,
The string returned by You should not modify the string returned by When you read the current locale for category To be sure you can use the returned string encoding the currently selected locale at a later time, you must make a copy of the string. It is not guaranteed that the returned pointer remains valid over time. When the locale argument is not a null pointer, the string returned
by If you specify an empty string for locale, this means to read the appropriate environment variable and use its value to select the locale for category. If a nonempty string is given for locale, then the locale of that name is used if possible. If you specify an invalid locale name, |
Here is an example showing how you might use setlocale
to
temporarily switch to a new locale.
#include <stddef.h>
#include <locale.h>
#include <stdlib.h>
#include <string.h>
void
with_other_locale (char *new_locale,
void (*subroutine) (int),
int argument)
{
char *old_locale, *saved_locale;
/* Get the name of the current locale. */
old_locale = setlocale (LC_ALL, NULL);
/* Copy the name so it won't be clobbered by setlocale
. */
saved_locale = strdup (old_locale);
if (saved_locale == NULL)
fatal ("Out of memory");
/* Now change the locale and do some stuff with it. */
setlocale (LC_ALL, new_locale);
(*subroutine) (argument);
/* Restore the original locale. */
setlocale (LC_ALL, saved_locale);
free (saved_locale);
}
Portability Note: Some ISO C systems may define additional
locale categories, and future versions of the library will do so. For
portability, assume that any symbol beginning with LC_
might be
defined in locale.h
.