小明思考

高性能服务器端计算
posts - 70, comments - 428, trackbacks - 0, articles - 0
  C++博客 :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理

G11N Developement (2) --- Linux Best Practice

Posted on 2006-06-26 16:57 小明 阅读(1471) 评论(0)  编辑 收藏 引用 所属分类: C/C++G11N/ICULinux
在linux/Unix平台上面做G11N的开发,大抵都会用到gettext库/工具集( ftp://ftp.gnu.org/gnu/gettext/ ) 和libiconv(http://www.gnu.org/software/libiconv/) ,前者是用于实现Resource bundle,而后者用于各种编码转化。

(注:这里没有考虑cross-platform)


1. 实现方法

a . 使用po文件作为资源文件 (建议编码是utf-8)
    一方面因为UTF-8兼容ANSI,另外一方面考虑到G11N的程序大部分使用utf-8输出,比如输出到database,web UI, file等等。

b. 使用getext从resource file ( mo文件)读到相应的L10N resource文件
   注意这里需要先setlocale来设置locale
#include <stdio.h>
#include 
<locale.h>
#include 
<libintl.h>

#define _(string) gettext (string)

int main(int argc, char **argv)
{
    
if (setlocale(LC_ALL, “”) == NULL) {
        fprintf(stderr, “setlocale() error.\n”);
        
return -1;
}
if (bindtextdomain(package, “/usr/share/locale”) == NULL) {
    fprintf(stderr, “bindtextdomain() error.\n”);
    
return –1;
}
    
if (textdomain(package) == NULL) {
        fprintf(stderr, “textdomain() error.\n”);
        
return –1;
}
    printf(“
%s\n”, _(“Hello, world!”));
    
return 0;
}


c.如果要输出到控制台(console),因为不是console都支持unicode output,所以推荐的方法是首先是把utf-8转化为本地编码,然后使用printf输出。不推荐使用wprintf进行输出,一方面是因为wchar_t的大小随编译器不同,不好控制。另外一方面,很多wprintf的实现也都是先把wchar_t[]转为本地编码,然后输出。转化编码使用libconv

d.如果要输出到web pages,database,file,编码推荐使用utf-8.

e.如果要输出本地化的日期和时间,使用API: strftime
#include <stdio.h>
#include 
<time.h>
int main(int argc, char **argv) 
{
    time_t t;
    
struct tm *ptm;
    
char buffer[100];

    memset(buffer, 
0sizeof(buffer));
    
if (time(&t) < 0) {
        fprintf(stderr, “time() error: 
%m\n”);
    }
    
if ((ptm = localtime(&t)) == NULL) {
        fprintf(stderr, “localtime() error: 
%m\n”);
    }
    strftime(buffer, 
sizeof(buffer), “%%X”, ptm);
    printf(“
%s\n”, buffer);
    
return 0;
}


f. 如果要输出本地化的数字和货币,使用API: strfmon
#include <stdio.h>
#include 
<monetary.h>

int main(int argc, char **argv)
{
    
char buffer[100];
    strfmon(buffer, 
sizeof(buffer), “%=*i", 12345.67);
    printf(“%s\n”, buffer);
    
return 0;
}


2.目录结构
/product
  /i18n
      /zh_TW
          your.mo
      /ja_JP 
          your.mo


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理