简体   繁体   中英

How to programmatically (C/C++) get Country code on Linux?

I'm porting my application into Linux (from Windows).

I have such code:


char buffer[32] = {0};

if ( GetLocaleInfoA(LOCALE_USER_DEFAULT, LOCALE_ICOUNTRY, buffer, _countof(buffer)) )
{
    std::string newPrefix(buffer);
    if ( !newPrefix.empty() && ( newPrefix != "-1" ) )
    {
        countryPrefix_ = newPrefix;
    }
}

I need a function which return "country/region code, based on international phone codes" (for example, "1" for USA & Canada, "61" for Australia etc.)
The country should be taken from OS' date/time settings (in Windows: Control Panel - Regional & language options).

  • there is no OS Wide locale setting for Unix. There can be a default used for users which don't overwrite it, but most users do overwrite it. And it is quite common to leave it as "C".

  • there is no standard C or C++ way to get the information you want.

  • the posix way of getting information related to the locale is to set the locale and the use nl_langinfo() (that returns a char* ). While there is no POSIX macro defined for the international phone code, glibc has an extension for it ( _NL_TELEPHONE_INT_PREFIX ).

Example:

#include <langinfo.h>
...
if (setlocale(LC_ALL, "") == NULL) {
   fprintf(stderr, "Unable to set locale.\n");
   abort();
}
printf("Telephone international prefix: %s\n", nl_langinfo(_NL_TELEPHONE_INT_PREFIX));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM