读取Unicode格式或者UTF-8或者ANSI格式txt中的内容

CString strFilePath;
    CFile mFile;
    if(!mFile.Open(L“Pos.txt”,CFile :: modeRead | CFile :: typeBinary))
    {
        MessageBox(_T(“无法打开文件:”)+ strFilePath,_T(“错误”),MB_ICONERROR | MB_OK );
        PostQuitMessage(0);
    }

    BOOL m_isUnicode = FALSE;
    BOOL m_isUTF_8Code = FALSE;

    字节头[3]; //获取头部内容
    字符串strContents; //文件内容
    UINT FileSize; //文件大小
    char * buf; // temp 
    mFile.Read(head,3);
    //判断txt中数据是Unicode格式还是UTF-8还是ANSI格式
    if((head [0] == 0xff && head [1] == 0xfe)||(head [0] == 0xfe && head [1] == 0xff))//测试文件是Unicode?
    {
        m_isUnicode = true;
    }

    if((head [0] == 0xef && head [1] == 0xbb && head [2] == 0xbf)||(head [0] == 0xbf && head [1] == 0xbb && head [2] == 0xef))//测试文件是UTF-8 ??
    {
        m_isUTF_8Code = true;
    }

    if(m_isUTF_8Code)//读取UTF-8文件
    {

        FileSize =(UINT)mFile.GetLength();
        buf = new char [FileSize];
        mFile.Seek(3,CFile :: begin); // 0xefbbbf
        mFile.Read(buf,FileSize);
        int size = MultiByteToWideChar(CP_UTF8,0,buf,FileSize + 1,NULL,0);
        wchar_t * pWideChar = new wchar_t [size + 1];
        MultiByteToWideChar(CP_UTF8,0,buf,FileSize + 1,pWideChar,size);
        // strContents = CString(pWideChar).GetBuffer(0);
        删除[] buf;
        删除[] pWideChar;

    }
    else if(m_isUnicode)//读取Unicode文件;
    {
        int i = 1;
        wchar_t wch; // for unicode
        wchar_t wstr [300]; // for unicode
        memset((void *)wstr,0,sizeof(char)*(2 * 300));
        mFile.Seek(2,CFile :: begin); // 0xfffe
        while(mFile.Read((char *)&wch,2)> 0)
        {
            if(wch == 0x000D)// by line
            {
                //更改为ANSI
                int nLen = i;
                buf = new char [2 * nLen];
                memset((void *)buf,0,sizeof(char)*(2 * nLen));
                WideCharToMultiByte(CP_ACP,0,wstr,-1,buf,2 * nLen,NULL,NULL);
                buf [2 * nLen - 1] ='\ 0';
                // buf就是读取的txt中每行的数据
                strContents + = buf;
                删除[] buf;
                i = 0;
            }
            else
            {
                wstr [i ++] = wch;
                CString str = wstr;

            }
        }
    }
    否则//读取ANSI文件
    {
        文件大小=(UINT)mFile.GetLength();
        buf = new char [FileSize];

        while(mFile.Read(buf,FileSize)> 0)
        {
            strContents = buf;

        }
        delete [] buf;
    }
    mFile.Close();

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值