Chinaunix首页 | 论坛 | 博客
  • 博客访问: 110477
  • 博文数量: 23
  • 博客积分: 1464
  • 博客等级: 上尉
  • 技术积分: 231
  • 用 户 组: 普通用户
  • 注册时间: 2006-11-06 16:44
文章分类

全部博文(23)

文章存档

2014年(4)

2011年(3)

2009年(2)

2008年(14)

我的朋友

分类:

2008-12-25 14:01:15

   //判断文件是那种类型编码
    CFile file;
    if(file.Open(szFileName ,CFile::modeRead))
    {
        unsigned char p_buf;////先读的字节

        //先读上2个字节
        file.Read(&p_buf,1);
        int  p = p_buf * 256;
        file.Read(&p_buf,1);
        p = p_buf + p;
        //文件读指针回到首位
        file.Seek(0, CFile::begin);
        switch(p)  
        {  
            case  0xefbb://如果是这个开头就是UTF8编码
                {
                    break; 
                }
            case  0xfffe:  ////如果是这个开头就是 unicode小端格式
                {
                   break;
                }
            case  0xfeff:  //"Unicode  big  endian"
                                  //处理方法同上面
                  break; 
            default:  //ANSI
                {
                   break;
                }
        }
    }

                    
//UTF8 to Unicode
    CFile file;
    if(file.Open(szFileName,CFile::modeRead))
    {
         long lenx=(long)file.GetLength();
         char* pHtml=new char[lenx+1];
         long lRead=file.Read(pHtml,lenx);
         file.Close();
         //预转换,得到所需空间的大小
         int wcsLen = ::MultiByteToWideChar(CP_UTF8, NULL, pHtml, lenx+1, NULL, 0);
         //分配空间要给'\0'留个空间,MultiByteToWideChar不会给'\0'空间
         wchar_t* wszString = new wchar_t[wcsLen + 1];
         //转换
         ::MultiByteToWideChar(CP_UTF8, NULL, pHtml, lenx+1, wszString, wcsLen);
         //最后加上'\0'
         wszString[wcsLen] = '\0';
         delete pHtml;
   }

//unicode to UTF8
    //预转换,得到所需空间的大小,这次用的函数和上面名字相反csContent为UTF8编码
    int u8Len = ::WideCharToMultiByte(CP_UTF8, NULL, csContent, wcslen(csContent), NULL, 0, NULL, NULL);
    //同上,分配空间要给'\0'留个空间
    //UTF8虽然是Unicode的压缩形式,但也是多字节字符串,所以可以以char的形式保存
    char* szU8 = new char[u8Len + 1];
    //转换
    //unicode版对应的strlen是wcslen
    ::WideCharToMultiByte(CP_UTF8, NULL, csContent, wcslen(csContent), szU8, u8Len, NULL, NULL);
    //最后加上'\0'
    szU8[u8Len] = '\0';
阅读(788) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~