utf 8 - How to convert encoding type of multiple .txt & .pro files from ANSI to UTF-8 -
i have multiple .txt
files encoding format ansi in folder named folder1
. need convert utf-8
encoding type files in empty folder name folder2
. don't want convert files 1 one - want convert them @ time.
use multibytetowidechar() cp_acp convert data widechar , use widechartomultibyte() cp_utf8 convert in utf8 if talking c++
static int to_utf8encodefile(std::wstring filepath) { int error_code = 0; //read text file 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; }
above code converts single ansi file utf8 , can use cp_utf16 want , hope code helpfull
Comments
Post a Comment