使用 MultiByteToWideChar() 和 CP_ACP 将数据转换为 WideChar,然后使用 WideCharToMultiByte() 和 CP_UTF8 在 utf8 中转换(如果我们在谈论 c++)
static int to_utf8EncodeFile(std::wstring filePath)
{
int error_code = 0;
//read text file which will be in ANSI encoding type
std::string fileName(filePath.begin(), filePath.end());
std::string fileContent;
fileContent = readFile(fileName.c_str());
if(fileContent.empty())
{
return GetLastError();
}
int wchars_num = MultiByteToWideChar( CP_ACP , 0 , fileContent.c_str() , -1, NULL , 0 );
wchar_t* wstr = new wchar_t[wchars_num];
error_code = MultiByteToWideChar( CP_ACP , 0 , fileContent.c_str() , -1, wstr , wchars_num );
if(error_code == 0)
{
delete [] wstr;
return GetLastError();
}
int size_needed = WideCharToMultiByte(CP_UTF8 , 0, &wstr[0], -1, NULL, 0, NULL, NULL);
std::string strTo( size_needed, 0 );
error_code = WideCharToMultiByte(CP_UTF8 , 0, &wstr[0], -1 , &strTo[0], size_needed, NULL, NULL);
delete [] wstr;
if(error_code == 0)
{
return GetLastError();
}
//Write utf-8 file
std::ofstream utf_stream(filePath.c_str());
utf_stream << strTo.c_str();
utf_stream.close();
return error_code;
}
以上代码将单个 ANSI 文件转换为 UTF8,你可以使用任何你想要的 CP_UTF16,
希望代码会有所帮助