How to get the locale of the current user in OSX using C++

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)

Answer

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();
CFStringRef 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>

Leave a Reply

Your email address will not be published. Required fields are marked *