C programming locale.h function - char *setlocale(int category, const char *locale)

The C programming setlocale function is defined in the locale.h header file and is used to set the current locale of the program. The setlocale function takes two arguments: category and locale.

The category argument is an integer constant that specifies the category of the locale to be set. There are several predefined constants for different categories, including:

  • LC_ALL: Sets the entire locale.
  • LC_COLLATE: Sets the locale for string collation.
  • LC_CTYPE: Sets the locale for character classification and conversion.
  • LC_MONETARY: Sets the locale for formatting monetary values.
  • LC_NUMERIC: Sets the locale for formatting numeric values.
  • LC_TIME: Sets the locale for formatting dates and times.

The locale argument is a string that specifies the name of the locale to set. The format of the locale string is typically a combination of language and country codes, separated by an underscore. For example, "en_US" for English as spoken in the United States, or "fr_FR" for French as spoken in France.

The setlocale function returns a string that represents the previously set locale, or NULL if the specified locale is not supported.

Here's an example usage of the setlocale function to set the locale for string collation:

#include <locale.h>
#include <stdio.h>
#include <string.h>

int main() {
    char str1[] = "apple";
    char str2[] = "Apple";
    
    // Set the locale for string collation to "en_US.UTF-8"
    setlocale(LC_COLLATE, "en_US.UTF-8");
    
    // Compare the two strings using the current locale
    if (strcoll(str1, str2) < 0) {
        printf("%s comes before %s\n", str1, str2);
    } else {
        printf("%s comes before %s\n", str2, str1);
    }
    
    return 0;
}
Source:w‮tfigi.ww‬idea.com

In this example, the setlocale function is used to set the locale for string collation to "en_US.UTF-8". The strcoll function is then used to compare two strings (str1 and str2) using the current locale, and the result is printed to the console.