MFC字符Unicode转UTF-8

unicode的环境下,写中文到文件,会出现乱码。

解决方法下面两个函数。 

EncodeToUTF8  写入的时候调用

UTF8ToEncode 读取的时候调用

MultiByteToWideChar                           WideCharToMultiByte 实现原理就是这两个函数。 不知到哪位仁兄写的。

 

char* EncodeToUTF8(const char* mbcsStr)
{
 wchar_t*  wideStr;
 char*   utf8Str;
 int   charLen;

 charLen = MultiByteToWideChar(CP_UTF8, 0, mbcsStr, -1, NULL, 0);
 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);

 utf8Str = (char*) malloc(charLen);

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

 free(wideStr);
 return utf8Str;

}
char* UTF8ToEncode(const char* mbcsStr)
{
 wchar_t*  wideStr;
 char*   unicodeStr;
 int   charLen;

 charLen = MultiByteToWideChar(CP_UTF8, 0, mbcsStr, -1, NULL, 0);  
 wideStr = (wchar_t*) malloc(sizeof(wchar_t)*charLen);
 MultiByteToWideChar(CP_UTF8, 0, mbcsStr, -1, wideStr, charLen); 

 charLen =WideCharToMultiByte(CP_ACP, 0, wideStr, -1, NULL, 0, NULL, NULL); 
 unicodeStr = (char*)malloc(charLen);
    WideCharToMultiByte(CP_ACP, 0, wideStr, -1, unicodeStr, charLen, NULL, NULL); 

 free(wideStr);
 return unicodeStr;
}

你可能感兴趣的:(Windows/VC/MFC)