ASCII 转换为UNICODE

 

 

方法一: 使用MultiByteToWideChar

 

         


CFile file(strPath,CFile::modeRead|CFile::typeBinary);

 

int num=file.GetLength();   // 得到的是文件字节(BYTE)的数目,而不是字数
char *read;

read=new char[num];

file.Read(read,num);   //将字符串从文件中读取到read动态数组中,num表示从文件中读取num个BYTE

 

 

WCHAR *wword;      //Unicode 宽字符类型
wword=new WCHAR[num];

if (wword==NULL)
{
 free(wword);
}

memset(wword,0,num*sizeof(WCHAR));    // 对分配的空间进行初始化为0, 初始化为0很重要,因为cstring也是以0为结束符的
MultiByteToWideChar(CP_ACP,0,read,num,wword,num); //将保存在read数组中的num个字节 转换到 wword中,  wword空间可能会有剩余,所以应该先对其空间进行初始化为0的操作

 

for (int i=0;i<num;i++)
{
 strText+=wword[i];                         

}       //将Unicode宽字符数组中的文字 置入CString串中,因CString以0为结尾,所以当wword剩余空间对cstring字符串没影响,因为其已经被初始化为0了 

 

file.Close();

delete wword;
delete read;
m_RichEdit.SetWindowText(strText);

 

源码:

 

CFileDialog dlgFile(TRUE,NULL,NULL,OFN_HIDEREADONLY|OFN_OVERWRITEPROMPT,L"All Files(*.*)|*.*||"); CString strPath,strText=L""; if (dlgFile.DoModal()==IDOK) { strPath=dlgFile.GetFileName(); } CFile file(strPath,CFile::modeRead|CFile::typeBinary); int num=file.GetLength(); char *read; read=new char[num]; file.Read(read,num); WCHAR *wword; wword=new WCHAR[num]; if (wword==NULL) { free(wword); } memset(wword,0,num*sizeof(WCHAR)); MultiByteToWideChar(CP_ACP,0,read,num,wword,num); for (int i=0;i<num;i++) { strText+=wword[i]; } file.Close(); delete wword; delete read; m_RichEdit.SetWindowText(strText);

 

 

 

方法二:使用USES_CONVERSION  

 

            此方法比较简单

    

            共分两部:

            第一步:   用一数组保存待转换的字符串,字符串必须以'/0'结束

 

            第二步:  开始转换,将结果保存在CString 类对象中

           

 

CFile file(strPath,CFile::modeRead|CFile::typeBinary);

 

int length=file.GetLength();

 

char *read=new char[length+1];   //  定义一动态数组,数组大小为文件长度+1,这个1用来存放文字串的结束符'/0'

 

file.Read(read,length);

read[length]='/0';         //   必须要加字符串结束符,否则转换会出错

 

USES_CONVERSION;      // 开始转换

CString str=A2W(read);

m_RichEdit.SetWindowText(str);

 

源码:

CFile file(strPath,CFile::modeRead|CFile::typeBinary); int length=file.GetLength(); char *read=new char[length+1]; file.Read(read,length); read[length]='/0'; USES_CONVERSION; CString s=A2W(read); m_RichEdit.SetWindowText(s);

 

 

 

你可能感兴趣的:(File,null,delete,byte)