1. 程式人生 > >指定輸出文字為utf-8編碼格式

指定輸出文字為utf-8編碼格式

1.有時我們編碼生成輸出的一些內容,通過軟體開啟可能會出現亂碼的現象或者出現格式上的問題需要將其輸出轉換我utf-8的編碼格式。在這裡提供一種轉換的方法。

BOOL CtreetoxmlDlg::WriteUTF(CFile &file, CString sTxt)
{
	LPCSTR pUtf8 = LPCSTR(sTxt);
   	UINT nLength=strlen(pUtf8);
	int nChar = ::MultiByteToWideChar(CP_ACP,0, pUtf8, nLength,NULL, 0);
	CStringW tempBuffer;
	nChar = ::MultiByteToWideChar(CP_ACP, 0, pUtf8, nLength, (LPWSTR)tempBuffer.GetBufferSetLength(nChar), nChar);
	
	int u8Len = ::WideCharToMultiByte(CP_UTF8, NULL, tempBuffer, wcslen(tempBuffer), NULL, 0, NULL, NULL);
	char* szU8 = new char[u8Len + 1];
	::WideCharToMultiByte(CP_UTF8, NULL, (LPCWSTR)tempBuffer, wcslen(tempBuffer), szU8, u8Len, NULL, NULL);
	szU8[u8Len] = '\0';
	file.Write(szU8, u8Len);
	return TRUE;
}