C setlocale()

The setlocale() function defined in the locale.h header file. It helps to set or read location-dependent information for the current program.


char *setlocale(int category, const char *locale) #where category will be any of the macro
 

setlocale() Parameters:

The setlocale() function takes two parameters.Category macro for setlocale() are as below.

  • LC_ALL  - Selects all the C locale
  • LC_COLLATE -   Selection of the collation category
  • LC_CTYPE  -  Selects the character classification category
  • LC_MONETARY -   Selects the monetary formatting category
  • LC_NUMERIC  -  Selects the numeric formatting category
  • LC_TIME  -  Selects the time formatting category
Parameter Description Required / Optional
category Indicates the locale information of the program is to be affected Required
locale A system-specific locale identifier.setlocale() queries the current C locale if it is a null pointer. Required

setlocale() Return Value

It returns a pointer to the string identifying the C locale after applying the changes.

Input Return Value
On success a pointer to the string
On failure a null pointer

Examples of setlocale()

Example 1: Working of setlocale() function in C


#include <stdio.h>
#include <locale.h>
#include <time.h>
int main () {
   time_t ctime;
   struct tm *timer;
   char ar[80];

   time( &ctime;);
   timer = localtime( &ctime; );

   printf("Locale : %s\n", setlocale(LC_ALL, "en_GB"));
   strftime(ar,80,"%c", timer );
   printf("Date : %s\n", ar);

  
   printf("Locale : %s\n", setlocale(LC_ALL, "de_DE"));
   strftime(ar,80,"%c", timer );
   printf("Date : %s\n", ar);

   return(0);
}

Output:


Locale : en_GB                                                            
Date : Fri 05 Dec 2014 10:35:02 UTC                                       
Locale : de_DE                                                            
Date : Fr 05 Dez 2014 10:35:02 UTC

Example 2: How setlocale() function works in C?


#include <stdio.h>
#include <locale.h>
#include <time.h>
int main()
{
 char *st;
 setlocale(LC_ALL, "en_US.utf8");
 
 st = setlocale(LC_ALL, NULL);
    printf("Current locale: %s\n", st);
    printf("Changing locale\n");
 
 setlocale(LC_ALL, "en_GB.utf8");
 st = setlocale(LC_ALL, NULL);
 printf("Current locale: %s\n", st);
 
 return 0;
}

Output:


Current locale: en_US.utf8
Changing locale
Current locale: en_GB.utf8