4

I have a C++ application where I need to retrieve the locale of the current user. How can I do it with OSX Yosemite and newer?

I've tried something like setlocale(LC_CTYPE, NULL); but it just returns UTF-8 where my system is clearly in Spanish (es_AR)

Fernando
  • 2,131
  • 3
  • 27
  • 46
  • 1
    Have you tried [this](http://stackoverflow.com/questions/12170488/how-to-get-current-locale-of-my-environment)? – NathanOliver Aug 31 '16 at 17:27
  • I just tried, but it does not work with OSX. My code: setlocale(LC_ALL, ""); setlocale(LC_CTYPE, NULL); and the result is UTF-8 – Fernando Aug 31 '16 at 17:29

1 Answers1

5

After some try and error and lot of help from internet and other questions I did it.

If I want to get only the language.

CFLocaleRef cflocale = CFLocaleCopyCurrent();
auto value = (CFStringRef)CFLocaleGetValue(cflocale, kCFLocaleLanguageCode);    
std::string str(CFStringGetCStringPtr(value, kCFStringEncodingUTF8));
CFRelease(cflocale);

This way, at str I'll get a std::string with the language. If I need something else, I can replace kCFLocaleLanguageCode with any other constant from CFLocale

Also I needed the header #include <CoreFoundation/CoreFoundation.h>

Fernando
  • 2,131
  • 3
  • 27
  • 46