CFile 读取 UTF-8

该段代码展示了如何使用CFile类从UTF-8编码的文件中读取内容。首先检查文件头是否为UTF-8 BOM,然后读取整个文件到缓冲区,再将缓冲区的内容转换为宽字符字符串,最后返回转换后的字符串。
摘要由CSDN通过智能技术生成

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;
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值