asm, c, c++ are my all
-- Core In Computer
posts - 139,  comments - 123,  trackbacks - 0
[转]深入 printf / wprintf / console下的unicode output

1. printf 只能提供ANSI/MB 的输出,不支持输出unicode stream.
例如:
wchar_t test[] = L " 测试1234 " ;
printf(
" %s " ,test);
是不会正确输出的


2.wprintf 同样不会提供unicode output,
   但是他会把wchar_t的string转为locale的SB/MB字符编码,然后输出
例如:
wchar_t test[]  =  L " 测试Test " ;
wprintf(L
" %s " ,test);
会输出??1234之类的字符串,或者不输出任何结果
因为wprintf没有办法把L"测试Test"转为默认的ANSI,需要设置locale
setlocale(LC_ALL, " chs " );
wchar_t test[] 
=  L " 测试Test "
;
wprintf(L
" %s " ,test);
会有正确的输出

综上: 
CRT I/O functions do not provide Unicode output.

3. Window console自从NT4就是一个真正的unicode console
不过输出unicode string,只有使用Windows API, WriteConsoleW
例如:
wchar_t test[]  =  L " 测试1234 " ;
DWORD ws;
WriteConsoleW(GetStdHandle(STD_OUTPUT_HANDLE),test,wcslen(test),
& ws,NULL);
可以正确的输出而不需要设置locale,因为是真正的unicode的输出,跟codepage无关

4. 如何实现跨平台的console output
    不要使用wchar_t和wprintf,因为这些都依赖于编译器.
     ICU是IBM的一个成熟的跨平台支持unicode的libary,推荐使用

以下是ICU的uprintf实现

void  uprintf( const  UnicodeString  & str) {
    
char   * buf  =   0
;
    int32_t len 
=
 str.length();
    int32_t bufLen 
=  len  +   16
;
    int32_t actualLen;
    buf 
=   new   char [bufLen  +   1
];
    actualLen 
=  str.extract( 0 , len, buf /* , bufLen */ );  //  Default codepage conversion

    buf[actualLen]  =   0 ;
    printf(
" %s "
, buf);
    delete buf;
}
它也是先把Unicode string转化为本地的codepage,然后printf,虽然也不是unicode output,但是跨平台,大多数情况会工作得很好。
posted on 2006-06-22 02:11 Jerry Cat 阅读(394) 评论(0)  编辑 收藏 引用

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



<2006年9月>
272829303112
3456789
10111213141516
17181920212223
24252627282930
1234567

常用链接

留言簿(7)

随笔档案

最新随笔

搜索

  •  

最新评论

阅读排行榜

评论排行榜