在这里,我们遇到了很少使用的本地化属性。如果您将字符串输出为字符串(而不是原始数据),则可以让本地化自动执行适当的转换。
N.B.此代码未考虑wchar_t字符的字节序。
#include <locale>
#include <fstream>
#include <iostream>
#include "UTF16Facet.h"
int main(int argc,char* argv[])
{
UTF16Facet *unicodeFacet = new UTF16Facet();
const std::locale unicodeLocale(std::cout.getloc(), unicodeFacet);
std::wofstream saveFile;
saveFile.imbue(unicodeLocale);
saveFile.open("output.uni");
saveFile << L"This is my Data\n";
return(0);
}
文件: UTF16Facet.h
#include <locale>
class UTF16Facet: public std::codecvt<wchar_t,char,std::char_traits<wchar_t>::state_type>
{
typedef std::codecvt<wchar_t,char,std::char_traits<wchar_t>::state_type> MyType;
typedef MyType::state_type state_type;
typedef MyType::result result;
virtual result do_in(state_type &s,
const char *from,const char *from_end,const char* &from_next,
wchar_t *to, wchar_t *to_limit,wchar_t* &to_next) const
{
for(;(from < from_end) && (to < to_limit);from += 2,++to)
{
(*to) = L'\0';
reinterpret_cast<char*>(to)[0] = from[0];
reinterpret_cast<char*>(to)[1] = from[1];
}
from_next = from;
to_next = to;
return((from > from_end)?partial:ok);
}
virtual result do_out(state_type &state,
const wchar_t *from, const wchar_t *from_end, const wchar_t* &from_next,
char *to, char *to_limit, char* &to_next) const
{
for(;(from < from_end) && (to < to_limit);++from,to += 2)
{
to[0] = reinterpret_cast<const char*>(from)[0];
to[1] = reinterpret_cast<const char*>(from)[1];
}
from_next = from;
to_next = to;
return((to > to_limit)?partial:ok);
}
};