mfc中如何读取,保存编码为utf-8的文件

本文提供了在MFC中用于将UTF-8字符串转换为宽字符和从宽字符转换回UTF-8的函数示例。代码包括了`ANSIToUnicode`,`UnicodeToANSI`,`UTF8ToUnicode`和`UnicodeToUTF8`四个函数,这些函数利用Windows API进行字符串编码的转换。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

主要用到两个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( const char* 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( const wchar_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( const char* 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( const wchar_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;
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值