简体   繁体   中英

Testing locale on Ubuntu using setlocale() and gettext()

I am trying to write a program that prints an English message in French based on locale.

I wrote the following sample code:

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

int main()
{
    char *str = setlocale(LC_ALL, "fr_FR.UTF-8");
    if(str == NULL)
        printf("setlocale() cannot be honored");
    else
        printf("setlocale() return = %s \n", str);

    bindtextdomain("helloworld","/usr/share/locale");
    textdomain("helloworld");
    printf("%s", gettext("Hello!\n"));

    return 0; 
}

I checked the file /usr/share/i18n/SUPPORTED and can see fr is there:

fr_FR.UTF-8 UTF-8
fr_FR ISO-8859-1
fr_FR@euro ISO-8859-15

I also tried running sudo locale-gen fr-FR.UTF-8 . When I run locale on the command line, I see:

LANG=en_US.UTF-8
LANGUAGE=
LC_CTYPE="en_US.UTF-8"
LC_NUMERIC="en_US.UTF-8"
LC_TIME="en_US.UTF-8"
LC_COLLATE="en_US.UTF-8"
LC_MONETARY="en_US.UTF-8"
LC_MESSAGES="en_US.UTF-8"
LC_PAPER="en_US.UTF-8"
LC_NAME="en_US.UTF-8"
LC_ADDRESS="en_US.UTF-8"
LC_TELEPHONE="en_US.UTF-8"
LC_MEASUREMENT="en_US.UTF-8"
LC_IDENTIFICATION="en_US.UTF-8"
LC_ALL=

When I run my program, setlocale() returns NULL . Can anyone tell what I'm missing ?

Edit

When trying to for zh-CN , I also checked the contents of directory /usr/share/locale/zh-CN/LC_MESSAGES . The following listing appears:

apt.mo              gnome-panel-3.0.mo  iso_639.mo
debconf.mo          iso_15924.mo        language-selector.mo
dpkg.mo             iso_3166_2.mo       libapt-inst1.4.mo
e2fsprogs.mo        iso_3166.mo         libapt-pkg4.12.mo
example-content.mo  iso_4217.mo         update-notifier.mo
ghex-3.0.mo         iso_639_3.mo        xdg-user-dirs.mo

If locale -a doesn't show fr_FR locale, you do not have one installed on your system.

The best/easiest way to do it may slightly depends on the distro. This topic answers your question: https://askubuntu.com/questions/76013/how-do-i-add-locale-to-ubuntu-server

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