Eric
Eric

Reputation: 24866

c - setlocale() not working as expect

The following program use setlocale() to take locale settings from environment variable, and print time.

locale_test.c:

// locale test

#include <stdio.h>
#include <locale.h>
#include <time.h>

// locale test
void locale_test() {
    // use environment variable to get locale setting,
    setlocale(LC_ALL, "");

    char buf[26];
    time_t now = time(NULL);
    ctime_r(&now, buf);
    printf("time: %s", buf);

    char *time_locale = setlocale(LC_TIME, NULL);
    printf("current LC_TIME locale: %s\n", time_locale);
}

int main(int argc, char *argv[]) {
    locale_test();
    return 0;
}

Execute:

The question is:


Update - Solution:

According to comment & answer, following changes are made:

The new program:

// locale test

#include <stdio.h>
#include <locale.h>
#include <time.h>

// locale test
void locale_test() {
    // use environment variable to get locale setting,
    if(setlocale(LC_ALL, "") == NULL) {
        printf("error while setlocale()\n");
    }

    // get current LC_TIME
    char *time_locale = setlocale(LC_TIME, NULL);
    if(time_locale == NULL) {
        printf("error while setlocale()\n");
    } else {
        printf("LC_TIME: %s\n", time_locale);
    }

    // print time in locale,
    size_t buf_size = 50;
    char buf[buf_size];
    // char *format = "%F %T %z";
    char *format = "%A, %d %B %Y, %H:%M:%S %Z";

    time_t now = time(NULL);
    struct tm tm_now;
    localtime_r(&now, &tm_now);

    strftime(buf, buf_size, format, &tm_now);
    printf("time: %s\n", buf);
}

int main(int argc, char *argv[]) {
    locale_test();
    return 0;
}

Then execute:

That's work as expect.

Upvotes: 0

Views: 8887

Answers (1)

Joni
Joni

Reputation: 111219

You have to check the return value of setlocale, because it will fail if the locale string is invalid, the locale you want is not installed, or some other reason.

if (setlocale(LC_ALL, "") == NULL) {
    puts("Unable to set locale");
}

You can check what locales are available with locale -a. Maybe you do have a French locale installed, but you have to set it with fr_FR.utf8.

Then again, ctime output does not depend on the locale; the standard specifies its exact format, and it will always be in English. For localized output use strftime instead.

Upvotes: 6

Related Questions