C++ fstream 讀寫 unicode 檔案
阿新 • • 發佈:2018-12-31
所謂的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(),""
- 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 = newchar[size + 1];
- memset(buffer,0,sizeof
- 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
- }
- 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();
- staticconstBYTE 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);
- returntrue;
- }
- }