CFile、File读写UTF8

CString CSocketClientDlg::GotFile(CString filename)
{
    CFile fileR;
    CString strFile="";
    if(!fileR.Open(filename,CFile::modeRead|CFile::typeBinary))
    {
        return strFile;
    }
    BYTE head[3];
    fileR.Read(head,3);
    if(!(head[0]==0xEF && head[1]==0xBB && head[2]==0xBF))
    {
        fileR.SeekToBegin();
    }
    ULONGLONG FileSize=fileR.GetLength();
    char* pContent=(char*)calloc(FileSize+1,sizeof(char));
    fileR.Read(pContent,FileSize);
    fileR.Close();
    int n=MultiByteToWideChar(CP_UTF8,0,pContent,FileSize+1,NULL,0);
    wchar_t* pWideChar=(wchar_t*)calloc(n+1,sizeof(wchar_t));
    MultiByteToWideChar(CP_UTF8,0,pContent,FileSize+1,pWideChar,n);
    strFile=CString(pWideChar);
    free(pContent);
    free(pWideChar);

    return strFile;
}

void write_utf8()  
{  
    FILE* fp = fopen("test.txt", "wb+");  
  
    // 写入UTF-8的BOM文件头  
    char header[3] = {(char)0xEF, (char)0xBB, (char)0xBF};  
    fwrite(header, sizeof(char), 3, fp);  
  
    char* s = "hello, 你好!";  
    wchar_t wc[256];  
    // 将ANSI编码的多字节字符串转换成宽字符字符串  
    int n = MultiByteToWideChar(CP_ACP, 0, s, strlen(s), wc, 256);  
    if ( n > 0 )  
    {  
        wc[n] = 0;  
  
        char mb[1024];  
        // 将宽字符字符串转换成UTF-8编码的多字节字符串  
        n = WideCharToMultiByte(CP_UTF8, 0, wc, wcslen(wc), mb, 1024, NULL, NULL);  
        if ( n > 0 )  
        {  
            mb[n] = 0;  
            fwrite(mb, sizeof(char), strlen(mb), fp);  
        }  
    }  
  
    fclose(fp);  
} 

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值