【程式碼備忘】C++ fstream 讀寫 unicode 檔案
阿新 • • 發佈:2018-12-31
歡迎加入我們的QQ群,無論你是否工作,學生,只要有c / vc / c++ 程式設計經驗,就來吧!158427611
所謂的unicode檔案,無非就是在檔案頭部插入了 0xFFFE的標誌。。。讀寫的時候對應的讀寫 就可以了。
namespace fileStream { bool readFile_Unicode( const string &file ,wstring &destWstring) { destWstring.clear(); //setlocale(LC_ALL,"Chinese-simplified");//設定中文環境 locale &loc=locale::global(locale(locale(),"",LC_CTYPE)); std::ifstream filestream (file.c_str(), std::ios::in|std::ios::binary|std::ios::ate); filestream.seekg (0, std::ios::end); size_t size = (size_t)filestream.tellg(); filestream.seekg(0,ios::beg); char* buffer = new char[size + 1]; memset(buffer,0,sizeof(char)*(size + 1)); filestream.read (buffer, size); destWstring = (wchar_t*)buffer; destWstring.erase(size/2);//刪除末尾可能會出現的亂碼 /2 是為了unicode 之後 長度只有一半 filestream.close(); delete[] buffer; //setlocale(LC_ALL,"C");//還原 locale::global(loc); return !destWstring.empty(); } bool writeFile_Unicode( const string &file ,const wstring &writeWstring ) { //setlocale(LC_ALL,"Chinese-simplified");//設定中文環境 locale &loc=locale::global(locale(locale(),"",LC_CTYPE)); std::ofstream filestream(file.c_str(), std::ios::out | std::ios::binary | std::ios::ate); filestream.clear(); static const BYTE unicodeHead[]={0xFF,0xFE}; //unicode檔案標頭檔案 filestream.write((char *)unicodeHead,2); filestream.seekp(std::ios::end); filestream.write((char *)writeWstring.c_str(),writeWstring.length() * 2); filestream.close(); //setlocale(LC_ALL,"C");//還原 locale::global(loc); return true; } }
歡迎加入我們的QQ群,無論你是否工作,學生,只要有c / vc / c++ 程式設計經驗,就來吧!158427611