mbstowcs函数 [转载]

原文地址: http://blog.bitfly.cn/post/mbstowcs-func/

mbstowcs函数可以用了将multi-byte字符串转换为wide char字符串,是ISO/ANSI C标准函数。但是multi-byte受LC_CTYPE locale的变量的影响,需要设定为UTF-8才行。但是Windows上用setlocale没法设定为UTF-8,因此只能使用MultiByteToWideChar。

二者除了参数不同外,返回的size也不同(差一个结尾''的大小)。mbstowcs返回的长度不包含结尾'',MultiByteToWideChar则包含(准确的讲,是"MultiByteToWideChar does notnull-terminate an output string if the input string length is explicitlyspecified without a terminating null character. To null-terminate an outputstring for this function, the application should pass in -1 or explicitly countthe terminating null character for the input string.")。

完整代码:


#include  // for MultiByteToWideChar, WideCharToMultiByte
#else
#include  // for mbstocws, cwstombs
#endif

wchar_t* mb2wc(const char* mbstr)
{
	wchar_t* wcstr = NULL;

	// Get the size of wchar_t after converted
#ifdef WIN32
	int size = MultiByteToWideChar(CP_UTF8, 0, mbstr, -1, NULL, 0);
#else
	size_t size = mbstowcs(NULL, mbstr, 0);
#endif

	wcstr = new wchar_t[size+1];
	if (wcstr)
	{
		memset(wcstr, 0, size * sizeof(wchar_t));
#ifdef WIN32
		int ret = MultiByteToWideChar(CP_UTF8, 0, mbstr, -1, wcstr, size);
		if (ret == 0) // MultiByteToWideChar returns 0 if it does not succeed.
#else
		size_t ret = mbstowcs(wcstr, mbstr, size+1);
		if (ret == -1)
#endif
		{
			delete[] wcstr;
			wcstr = NULL;
		}
	}

	return wcstr;
}

char* wc2mb(const wchar_t* wcstr)
{
	char* mbstr = NULL;

	// Get the size of char after converted
#ifdef WIN32
	int size = WideCharToMultiByte(CP_UTF8, 0, wcstr, -1, NULL, 0, NULL, NULL);
#else
	size_t size = wcstombs(NULL, wcstr, 0);
#endif

	mbstr = new char[size+1];
	if (mbstr)
	{
		memset(mbstr, 0, size * sizeof(char));
#ifdef WIN32
		int ret = WideCharToMultiByte(CP_UTF8, 0, wcstr, -1, mbstr, size, NULL, NULL);
		if (ret == 0) // MultiByteToWideChar returns 0 if it does not succeed.
#else
		size_t ret = wcstombs(mbstr, wcstr, size+1);
		if (ret == -1)
#endif
		{
			delete[] mbstr;
			mbstr = NULL;
		}
	}

	return mbstr;
}

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值