CStdioFile ReadString The problem of garbled characters displayed in Unicode environment.

Source: Internet
Author: User

TXT text is a Unicode encoding format, but after ReadString, the characters are garbled. Here is the solution.


CString csetupform::gettxtfile (CString txtdir)//parameter is file path {

CStdioFile file;
if (file. Open (Txtdir,cfile::modenotruncate | Cfile::moderead | Cfile::typetext))
{
CString str;
CString textcontent=_t ("");
while (file. ReadString (str))
{
if (Readstringtounicode (str))//Here to be processed, otherwise the Chinese characters will not display correctly. function See below
textcontent=textcontent+_t ("\ r \ n") +str;
}
File. Close ();
return textcontent;
}
Else
{
Return _t ("");
}

}

This function I refer to others, but the original is problematic. Always show a "hafnium" word coming out. Check it out, the problem is that there is no character Terminator.

BOOL Readstringtounicode (CString &str)
{


char *szbuf = new char[str. GetLength () +1]; Quantity to be added 1


for (int i = 0; i < str. GetLength (); i++)
{
Szbuf[i] = (CHAR) str. GetAt (i);
}  
Szbuf[str. GetLength ()]= ';  //Here, you must add, otherwise, the end of the film will display a "hafnium" word.
//Uses_conversion;
//char * SZ=W2A (str. GetBuffer ());  //I've tried all these methods, I can't.
BOOL bok= chartounicode (szbuf, &STR);
Delete []szbuf;
return bok;
}

The

//This function is referenced by the original. No changes are required
/////////////////////////////////////////////////////////////////////////////////////////
// Converts a char character to a Unicode character
int chartounicode (char *pchin, CString *pstrout)
{
int nlen;
WCHAR *ptch;


if (Pchin = NULL)
{
return 0;
}


Nlen = MultiByteToWideChar (CP_ACP, 0, Pchin,-1, NULL, 0);//Get the desired cache number
Ptch = new wchar[nlen];//Request Cache space
MultiByteToWideChar (CP_ACP, 0, Pchin,-1, Ptch, nlen);//transcoding
Pstrout->format (_t ("%s"), Ptch);
delete [] ptch;


return nlen;
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.