zoukankan      html  css  js  c++  java
  • CStdioFile在UNICODE环境下读取文本行〔转〕

    版权声明:转载时请以超链接形式标明文章原始出处和作者信息及本声明
    http://zongtongyi.blogbus.com/logs/8372306.html

    CStdioFile file;
        if (!file.Open(m_File_Path, CFile::modeRead)) return;
        CString strLine;
        while (file.ReadString(strLine))  
        {
           //strLine处理
        }
    问题:
        CStdioFile在_MSBC环境下读取任何ANSI文本数据都没问题,在UNICODE环境下读取ANSI文本中的中文时就会显示乱码。
    原因:
        CStdioFile读取ANSI文本数据时按char类型读取,在_MSBC下可以直接填充到CString,在UNICODE环境下要先将char转 换成宽字符WCHAR,然后再填充到CString,即一个汉字的两个char将变成两个UNICODE字符WCHAR。
    解决办法:
        在UNICODE环境下file.ReadString(strLine)取得的数据实际上是char类型,但是存储在UNICODE字符串中。为了取得真实数据,必须对strLine进行处理。
    void function(CString &str)
    {
        char *szBuf = new char[str.GetLength()];
        for (int i = 0 ; i < str.GetLength(); i++)
        {
            szBuf[i] = str.GetAt(i);
        }
        CharToUnicode(szBuf , &str);
        delete []szBuf;
    }
        注:此函数在编译的时候会提示
                    warning C4244: '=' : conversion from 'unsigned short' to 'char', possible loss of data
                不用管它,丢失的数据是我们不需要的。
    ===================================================================================
    /////////////////////////////////////////////////////////////////////////////////////////
    // 将Char型字符转换为Unicode字符
    int CharToUnicode(char *pchIn, CString *pstrOut)
    {
        int nLen;
        WCHAR *ptch;
        if(pchIn == NULL)
        {
            return 0;
        }
        nLen = MultiByteToWideChar(CP_ACP, 0, pchIn, -1, NULL, 0);
        ptch = new WCHAR[nLen];
        MultiByteToWideChar(CP_ACP, 0, pchIn, -1, ptch, nLen);
        pstrOut->Format(_T("%s"), ptch);
        delete [] ptch;
        return nLen;
    }
    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    // 将Unicode字符转换为Char型字符
    int UnicodeToChar(CString &strIn, char *pchOut, int nCharLen)
    {
        if(pchOut == NULL)
        {
            return 0;
        }
        int nLen = WideCharToMultiByte(CP_ACP, 0, (LPCWSTR)strIn.GetBuffer(BUFFER_SIZE_KILO),-1, NULL, 0, NULL, NULL);
        nLen = min(nLen, nCharLen);
        WideCharToMultiByte(CP_ACP, 0, (LPCWSTR)strIn.GetBuffer(BUFFER_SIZE_KILO), -1, pchOut,
            nLen, NULL, NULL);
        if(nLen < nCharLen)
        {
            pchOut[nLen] = 0;
        }
        return nLen;
    }

  • 相关阅读:
    ElasticSearch基础4:相关度
    ElasticSearch基础3:全文搜索
    ElasticSearch基础2:查询和过滤初步
    ElasticSearch基础1:初步
    Kafka高级设计和架构,一文深化理解
    JAVA :Jpanel 控件 无法显示问题
    beansbinding NetBeans IDE 中 Swing数据绑定插件
    关于网页游戏断线重连的思路和demo求助
    http://www.classicdosgames.com/
    easyui validatebox 验证集合
  • 原文地址:https://www.cnblogs.com/me115/p/1715178.html
Copyright © 2011-2022 走看看