`
aigo
  • 浏览: 2537670 次
  • 性别: Icon_minigender_1
  • 来自: 宜昌
社区版块
存档分类
最新评论

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

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics