How to convert a UNICODE file to ANSI
Submitted by Date of Submission User Level
Bulent Ozkir Jan 22, 2001 Intermediate
I will illustrate a simple way to convert any UNICODE file to ANSI. This function will accept the first parameter as a full path to the source UNICODE file, and an file extension to the ANSI file to be created...
eg Usage:
fileUNICODEtoANSI ( _T("c:\text1.txt", _T(".del") );
// output ANSI file will be _T("c:\text1.txt.del") . you can work on it now. :)
NOTEs:
1) You can use memory mapped files instead if your file sizes are large and you do not want to create ANSI file companions, though, you want to handle all the stuff synchronously in virtual memory.
2) When using WildCharToMultiByte function the first 2 bytes were resundant. I think this was a helper design for the IsTextUnicode api function's correctness. So I jumped 2 bytes over before starting conversion as the third parameter. (LPCWSTR) (buffer+2) . If I am wrong, you can correct me...
int fileUNICODEtoANSI(const CString &str1, const CString &str2)
{
try
{
// open the UNICODE file
CFile file (str1, CFile::modeRead);
int iFileLen = file.GetLength ();
PSTR buffer = new char[iFileLen];
PSTR pMultiByteStr = new char[iFileLen/2];
BOOL bUsedDefaultChar;
file.Read (buffer, iFileLen);
// convert to ANSI string
WideCharToMultiByte(CP_ACP, 0, (LPCWSTR) (buffer+2), -1, pMultiByteStr, iFileLen/2, _T(" "), &bUsedDefaultChar);
file.Close();
// create the ANSI file
file.Open(str1 + str2, CFile::modeCreate | CFile::modeWrite);
file.Write(pMultiByteStr, iFileLen/2);
file.Close();
delete[] buffer;
delete[] pMultiByteStr;
}
catch (CFileException* e)
{
TCHAR szCause[255];
e->GetErrorMessage(szCause, 255);
AfxMessageBox(szCause);
e->ReportError ();
e->Delete ();
}
return 0;
}
--------------------------------------------------------------------------------
Bulent Ozkir is a Turkey based senior software engineer. He has worked as a senior support engineer for Microsoft from 1998 to 2000. In his over 5 years programming career he has been working on various programming technologies including VB, VC, Visual Interdev, JavaScript, ASP, HTML/DHTML, WMI, COM+, TCP/IP, IIS, SS3, MCIS25, ASP and SQL Server. His background includes B.A. Comp. Sc., MCSE + Internet and MCSD. See members area for more details.
--------------------------------------------------------------------------------