Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

C Library Function - newlocale()

C Library Function - newlocale()

C Standard Library - <locale.h> C Standard Library -

Description

newlocale() is a function in the C standard library used to create a new locale object. It allows a program to create a specific locale setting, which can be modified or extended based on an existing locale.

Declaration

The following is the declaration of the newlocale() function.



#include 



locale_t newlocale(int category_mask, const char *locale, locale_t base);

Parameters

- `LC_COLLATE_MASK`: Locale information related to string comparison. - `LC_CTYPE_MASK`: Locale information related to character classification and conversion. - `LC_MONETARY_MASK`: Locale information related to currency formatting. - `LC_NUMERIC_MASK`: Locale information related to number formatting. - `LC_TIME_MASK`: Locale information related to time formatting. - `LC_MESSAGES_MASK`: Locale information related to message display. - `LC_ALL_MASK`: All locale categories.

Return Value

Example

The following is sample code for creating and using a new locale object with newlocale():

Example

#include

#include

#include // Required when using GNU extensions

int

main

(

)

{

   

// Create a new locale object using the "en_US.UTF-8" locale setting

    locale_t newloc

=

newlocale

(

LC_ALL_MASK

,

"en_US.UTF-8"

,

(

locale_t

)

0

)

;

   

if

(

newloc

==

(

locale_t

)

0

)

{

       

perror

(

"newlocale"

)

;

       

return

1

;

   

}

   

// Set the current thread's locale object to the new one

    locale_t oldloc

=

uselocale

(

newloc

)

;

   

// Get and print the current locale information

   

struct

lconv

lc

=

localeconv

(

)

;

   

printf

(

"Decimal point character in new locale: %s\n"

,

lc

->

decimal_point

)

;

   

printf

(

"Thousands separator in new locale: %s\n"

,

lc

->

thousands_sep

)

;

   

// Restore the previous locale object

    uselocale

(

oldloc

)

;

   

// Free the new locale object

    freelocale

(

newloc

)

;

   

return

0

;

}

Let's compile and run the above program, which will produce the following result:



Decimal point character in new locale: .

Thousands separator in new locale: ,

Code Analysis

Create a new locale object

Set the thread locale object

Free the locale object

Notes

Summary

newlocale() The function allows creating and using new locale objects so that a program can handle different locale settings and localization needs. By combining newlocale(), uselocale() and freelocale() functions, programmers can manage and switch a program's localization information more flexibly, thereby supporting the development of internationalized applications.

C Standard Library - <locale.h> C Standard Library -