C++——MFC字符Unicode轉UTF-8

unicode的環境下,寫中文到文件,會出現亂碼。

//Unicode到UTF-8的轉換
char* UnicodeToUtf8(const char* mbcsStr)  
{    
	int charLen = MultiByteToWideChar(CP_UTF8, 0, mbcsStr, -1, NULL, 0);  
	wchar_t* wideStr = (wchar_t*) malloc(sizeof(wchar_t)*charLen);  
	MultiByteToWideChar(CP_ACP, 0, mbcsStr, -1, wideStr, charLen);  

	charLen = WideCharToMultiByte(CP_UTF8, 0, wideStr, -1, NULL, 0, NULL, NULL);  

	char* utf8Str = (char*) malloc(charLen);  

	WideCharToMultiByte(CP_UTF8, 0, wideStr, -1, utf8Str, charLen, NULL, NULL);  

	free(wideStr);  
	return utf8Str;  
}  
//UTF-8到Unicode的轉換
static int Utf8ToUnicode(const char* utf8, char*unicode)
{
	int len = MultiByteToWideChar(CP_UTF8, 0, utf8, -1, NULL, 0);
	wchar_t* wstr = new wchar_t[len+1];
	memset(wstr, 0, len+1);
	MultiByteToWideChar(CP_UTF8, 0, utf8, -1, wstr, len);
	memcpy(unicode, wstr, len);
	if(wstr) delete[] wstr;
	return len;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章