1. 程式人生 > >mfc中如何讀取,儲存編碼為utf-8的檔案

mfc中如何讀取,儲存編碼為utf-8的檔案

主要用到兩個Api:
MultiByteToWideChar
http://msdn.microsoft.com/en-us/library/ms776413.aspx
WideCharToMultiByte
http://msdn.microsoft.com/en-us/library/ms776420.aspx

ANSI <--> Unicode <--> UTF8

  1. /*程式碼如下*/
  2. Code Snippet
  3. wchar_t * ANSIToUnicode( constchar* str )
  4. {
  5. int    textlen ;
  6. wchar_t * result;
  7.       textlen = MultiByteToWideChar( CP_ACP, 0, str,-1,    NULL,0 );  
  8.       result = (wchar_t *)malloc((textlen+1)*sizeof(wchar_t));  
  9.       memset(result,0,(textlen+1)*sizeof(wchar_t));  
  10.       MultiByteToWideChar(CP_ACP, 0,str,-1,(LPWSTR)result,textlen );  
  11. return    result;  
  12. }
  13. char * UnicodeToANSI( constwchar_t *str )
  14. {
  15. char * result;
  16. int textlen;
  17. // wide char to multi char
  18.       textlen = WideCharToMultiByte( CP_ACP,    0,    str,    -1,    NULL, 0, NULL, NULL );
  19.       result =(char *)malloc((textlen+1)*sizeof(char));
  20.       memset( result, 0, sizeof(char) * ( textlen + 1 ) );
  21.       WideCharToMultiByte( CP_ACP, 0, str, -1, result, textlen, NULL, NULL );
  22. return result;
  23. }
  24. wchar_t
     * UTF8ToUnicode( constchar* str )
  25. {
  26. int    textlen ;
  27. wchar_t * result;
  28.       textlen = MultiByteToWideChar( CP_UTF8, 0, str,-1,    NULL,0 );  
  29.       result = (wchar_t *)malloc((textlen+1)*sizeof(wchar_t));  
  30.       memset(result,0,(textlen+1)*sizeof(wchar_t));  
  31.       MultiByteToWideChar(CP_UTF8, 0,str,-1,(LPWSTR)result,textlen );  
  32. return    result;  
  33. }
  34. char * UnicodeToUTF8( constwchar_t *str )
  35. {
  36. char * result;
  37. int textlen;
  38. // wide char to multi char
  39.       textlen = WideCharToMultiByte( CP_UTF8,    0,    str,    -1,    NULL, 0, NULL, NULL );
  40.       result =(char *)malloc((textlen+1)*sizeof(char));
  41.       memset(result, 0, sizeof(char) * ( textlen + 1 ) );
  42.       WideCharToMultiByte( CP_UTF8, 0, str, -1, result, textlen, NULL, NULL );
  43. return result;