您的位置:首页 > 其它

wcstombs 使用,支持中文档unicode

2013-12-02 08:03 169 查看

wcstombs 使用之二,支持中文当unicode

当你调试进入源码,你会发现wcstombs 这个函数是和locale有关的。locale如果设置不对,那么程序运行将不能得到预期结果。

当C语言程序初始化时(刚进入到 main() 时),locale 被初始化为默认的 C locale,其采用的字符编码是所有本地 ANSI 字符集编码的公共部分,是用来书写C语言源程序的最小字符集(所以才起locale名叫:C)。

也就是说,默认locale是C,字符集是ascii。

当我们的输入是一组带有中文或者其他字符的字符串时候,他就会截断。只会转化前面的ascii字符。

所以在中文路径下是不能work的。

如果我们存在中文路径,或者字符,想使用wcstombs该函数来将宽字符串转为多字节字符串,那么我们就得设置系统的当前环境的locale.

主要是使用setlocale这个函数以及两个标记 LC_CTYPE, LC_ALL.

示例代码如下:

[cpp]
view plaincopyprint?

void testTNL()
{
char* old_locale = _strdup(setlocale(LC_CTYPE,NULL)); //store the old locale

setlocale(LC_CTYPE,setlocale(LC_ALL,"")); //using the locale of the user env.

const unsigned int nMaxPathLen = 255;
wchar_t szPath[nMaxPathLen + 1] = {0};
GetModuleFileName(NULL, szPath, nMaxPathLen);
wchar_t *p = wcsrchr(szPath, '\\');
*p = 0;

unsigned int _Dsize = (nMaxPathLen + 1) * 2;
char *_Dest = new char[_Dsize];
memset(_Dest,0,_Dsize);

wcstombs(_Dest,szPath,_Dsize);

//restore the old locale.
setlocale(LC_CTYPE, old_locale);
free(old_locale);

delete[] _Dest;
_Dest = NULL;

}

void testTNL()
{
char* old_locale = _strdup(setlocale(LC_CTYPE,NULL)); //store the old locale
setlocale(LC_CTYPE,setlocale(LC_ALL,"")); //using the locale of the user env.

const unsigned int nMaxPathLen = 255;
wchar_t szPath[nMaxPathLen + 1] = {0};
GetModuleFileName(NULL, szPath, nMaxPathLen);
wchar_t   *p = wcsrchr(szPath, '\\');
*p = 0;

unsigned int _Dsize = (nMaxPathLen + 1) * 2;
char *_Dest = new char[_Dsize];
memset(_Dest,0,_Dsize);

wcstombs(_Dest,szPath,_Dsize);

//restore the old locale.
setlocale(LC_CTYPE, old_locale);
free(old_locale);

delete[] _Dest;
_Dest = NULL;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: