Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use strerror_l with current locale?

I'm fixing some Linux code which used strerror (not thread-safe) for multi-threading. I found that strerror_r and strerror_l are both thread-safe. Due to different definitions for strerror_r (depending on _GNU_SOURCE it is differently defined) I'd like to use the newer strerror_l function, but how am I supposed to obtain a locale_t object for the current locale? I'm not using iconv or anything, just plain libc, and I don't see how I can obtain a "default locale" object (I don't care in what language the error is printed, I just want a human readable string.)

like image 547
Anteru Avatar asked Jan 09 '15 10:01

Anteru


2 Answers

You could use POSIX uselocale:

strerror_l(errno, uselocale((locate_t)0));
like image 132
Daniel Le Avatar answered Nov 16 '22 02:11

Daniel Le


If you pass "" to the locale parameter newlocale will allocate a locale object set to the current native locale[1]

[1]http://pubs.opengroup.org/onlinepubs/9699919799/functions/newlocale.html

static  locale_t locale;

bool MyStrerrorInit(void)
{
    locale = newlocale(LC_CTYPE_MASK|LC_NUMERIC_MASK|LC_TIME_MASK|LC_COLLATE_MASK|
                       LC_MONETARY_MASK|LC_MESSAGES_MASK,"",(locale_t)0);

    if (locale == (locale_t)0) {
       return false;
    }

    return true;
}

char * MyStrerror(int error)
{
    return strerror_l(error, locale);
}
like image 25
clockley1 Avatar answered Nov 16 '22 02:11

clockley1