参考了示例。
class WOFSTREAM : public std::ofstream
{
public:
WOFSTREAM()
{
}
WOFSTREAM(const wchar_t *path)
{
setlocale(LC_ALL,"");
size_t sz=-1;
char szPath[MAX_PATH]={0};
wcstombs_s(&sz,szPath,sizeof(szPath),path,_TRUNCATE);
cout<<<"\n";
open(szPath,ios::binary);//注意此处如不指定binary,ostream对象被默认视为对文本进行操作,会额外在行末添加字符:0x0D
this->WriteBOM();
setlocale(LC_ALL,"C");
}
WOFSTREAM& operator <<(const wchar_t* text)
{
const char *pData = (const char *)text;
const unsigned int length = wcslen(text) * sizeof(text[0]);
write(pData, length);
return *this;
}
WOFSTREAM& operator <<(unsigned short ch)
{
const char *pData = (char *)&ch;
const unsigned int length = sizeof(ch);
write(pData, length);
return *this;
}
WOFSTREAM& operator<<(WOFSTREAM& (*pfunc)(WOFSTREAM&))
{
return ((*pfunc)(*this));
}
protected:
void WriteBOM()
{
const static wchar_t BOM = 0xfeff;
write((const char *)&BOM, sizeof(BOM));
}
};
WOFSTREAM& endl(WOFSTREAM& wf)//重载换行符
{
wf<<0x000D<<0x000A;
return wf;
}
//使用:
int __cdecl main()
{
WOFSTREAM wf2(L"xx2.txt");
if (wf2.good())
{
wf2<<
wf2<
wf2.flush();
wf2.close();
}
else
{
cout<<"bad!"<
}
getchar();
return 1;
}