0

I want to store the locale name returned by the setlocale() function on Linux. As in Windows platform, max locale size is defined as LOCALE_NAME_MAX_LENGTH, Is there any similar macro defined for Linux? Also, I need to use same buffer on both the mentioned platforms.

char buffer[];
buffer = setlocale(LC_ALL, NULL);
confucius_007
  • 186
  • 1
  • 15
  • 1
    I’m not sure there’s a comparable equivalent. Locales in Linux can consist of concatenations of path names identifying individual locale files (https://www.gnu.org/software/libc/manual/html_node/Locale-Names.html), which suggests there’s no fixed upper bound. – templatetypedef Jun 30 '20 at 06:48
  • 2
    Why is the pointer itself not enough, i.e. why copy it into your program's storage? – dedObed Jun 30 '20 at 07:51

1 Answers1

4

The procedure you suggested in your question won’t work. You cannot assign setlocale’s return value (type char *) to a local array:

error: incompatible types in assignment of ‘char*’ to ‘char [10]’
  buffer = setlocale(LC_ALL, NULL);
                                 ^

You must assign the return value to a pointer, then you can examine its actual length using strlen and copy it to your array using strcpy:

#include <locale.h>  // setlocale
#include <string.h>  // strlen, strcpy
#include <stdio.h>   // printf

int main()
{
    char* pLocale;
    pLocale = setlocale(LC_ALL, NULL);
    char buffer[strlen(pLocale)+1];  // + 1 char for string terminator, see https://stackoverflow.com/a/14905963/711006
    strcpy(buffer, pLocale);
    printf("%s\n", buffer);
    return 0;
}

See it online.

The above is actually a C-compatible code. If you’re using C++, you can use setlocale’s return value to directly initialize a std::string without managing a char array manually:

#include <locale.h>  // setlocale
#include <iostream>

int main()
{
    std::string locale = setlocale(LC_ALL, NULL);
    std::cout << locale << std::endl;
    return 0;
}

See it online.

Melebius
  • 6,183
  • 4
  • 39
  • 52