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; }
相关文章推荐
- 【网络协议】HTTP协议笔记
- Moderate 不用比较符返回较大的数 @CareerCup
- 修改Ruby的config.yml文件
- mongodb分布式集群架构
- 黑马程序员----Java概述
- 2013年12月2日 周一
- LeetCode Substring with Concatenation of All Words暴力法暴力法更加暴力的方法
- P2P小贷网站业务数据流程分享
- chrome浏览器-Toolbar工具条不显示
- UVA 699 - The Falling Leaves
- hdu 4791 长沙现场赛A题
- STRUTS2 作用域、参数、响应对象
- Moderate 阶层的结尾0个数 @CareerCup
- Google adsense帐户被封到解封全过程
- 当你的才华还撑不起你的野心时,那你就应该静下心来学习。
- OpenCV4Android+JNI开发快速上手入门
- android NDK开发环境搭建
- 数据结构CCArray
- Think Pad T410键盘溅水有惊无险
- Moderate 判断井字游戏的胜利 @CareerCup