现在的位置: 首页 > 综合 > 正文

VC读取utf-8格式文本文件

2013年09月17日 ⁄ 综合 ⁄ 共 824字 ⁄ 字号 评论关闭

读取UTF-8格式文本文件
去掉文件头的三个字节,先将文本数据读到char数组之中,然后将多字节UTF8字符串转换成宽字符的UNICODE字符串,然后将UNICODE字符串转换成char型字符串或者直接复制到CString中(UTF-8char都属于MultiByte char,不能直接相互转换)
BOOL ReadUTF8StringFile(CString Path, CString& str)
{

    CFile fileR;
    if(!fileR.Open(Path,CFile::modeRead|CFile::typeBinary))
    {
        MessageBox(NULL,_T("无法打开文件:")+Path,_T("错误"),MB_ICONERROR|MB_OK);
        return false;
    }
    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);
    str=CString(pWideChar);
    free(pContent);
    free(pWideChar);
    return true;

}


抱歉!评论已关闭.