使用Unicode写文本文件:一个简单类的示例

参考了http://forums.codeguru.com/showthread.php?457106-Unicode-text-file示例。

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<<szPath<<"\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<<L"一个世界一个梦想"<<endl;

		wf2<<L"one world one dream";

		wf2.flush();

		wf2.close();

	}

	else

	{

		cout<<"bad!"<<endl;

	}

getchar();

return 1;

}

你可能感兴趣的:(unicode)