From the third degree: http://www.disandu.com /? P = 875
// Today, I wrote a piece of code to output text to a file. At the beginning, I used cfile to output Chinese characters, which always showed garbled characters. Baidu (Google was walled, the tutorials on the Internet basically only know one of them, and most of them only focus on the attention points of the output file in the byte sequence mark and the calculated width character length, but do not mention the most critical step of character conversion. The following code outputs both UTF-8 and ANSI (GBK encoding on Simplified Chinese Windows) encoded text files.
//
// Write UTF-8 text
// A cfileexception may be thrown in the following file operations
Try{
Cstdiofile hfile (strfilepath, cfile: modereadwrite );
If(Hfile. m_hfile)
{
DWORD dwfilelen = hfile. getlength ();
If(0 = dwfilelen) // when the file is empty, write the UTF bytecode mark.
{
Const Unsigned CharLeadbytes [] = {0xef, 0xbb, 0xbf };
Hfile. Write (leadbytes,Sizeof(Leadbytes ));
}
IntNsclen = (Int) Wcslen (lpstrword );
Cstringa utf8string (lpstrword );
IntNbuflen = (nsclen + 1) * 6;
Lpstr buffer = utf8string. getbuffersetlength (nbuflen );
// Convert Unicode to utf8
// The header file of the function atlunicodetoutf8 is required: <atlenc. h>
IntNlen = atlunicodetoutf8 (lpstrword, nsclen, buffer, nbuflen); // int nlen = utf8string. getlength ();
Buffer [nlen] = 0;
Utf8string. releasebuffer ();
// Write an object
Hfile. seektoend ();
Hfile. Write (lpcstr) utf8string, nlen );
Hfile. Write ("/R/N", 2 );
Hfile. Close ();
}
}
Catch(Cfileexception * pexception)
{
Cstring strmsg;
Tchar szerrormessage [512];
If(Pexception-> geterrormessage (szerrormessage,
Sizeof(Szerrormessage )/Sizeof(* Szerrormessage), 0 ))
Strmsg. Format (_ T ("(% s: % d)/n % s"), _ T (_ file _), _ line __, szerrormessage );
Else
Strmsg. Format (_ T ("(% s: % d)"), _ T (_ file _), _ line __);
Afxmessagebox (strmsg );
}
//////////////////////////////////////// /////////////////////////////////////
//////////////////////////////////////// /////////////////////////////////////
// Write ANSI text:
Try{
Cstdiofile hfile (strheimaiusrlibpath, cfile: modereadwrite );
If(Hfile. m_hfile)
{
// Assign the Unicode string to the cstringa in ANSI format for Unicode => ANSI Conversion
Cstringa utf8string (lpstrword );
IntNlen = utf8string. getlength ();
// Write an object
Hfile. seektoend ();
Hfile. Write (lpcstr) utf8string, nlen );
Hfile. Write ("/R/N", 2 );
Hfile. Close ();
}
}
Catch(Cfileexception * pexception)
{
Cstring strmsg;
Tchar szerrormessage [512];
If(Pexception-> geterrormessage (szerrormessage,Sizeof(Szerrormessage )/Sizeof(* Szerrormessage), 0 ))
Strmsg. Format (_ T ("(% s: % d)/n % s"), _ T (_ file _), _ line __, szerrormessage );
Else
Strmsg. Format (_ T ("(% s: % d)"), _ T (_ file _), _ line __);
Afxmessagebox (strmsg );
}