在VS2008中,如果项目设置了unicode字符集,把中文输出到文件中经常会遇到错误。
在MFC项目中,可以使用以下语句来实现unicode到多字节字符的转换:
- USES_CONVERSION;
- CString strLog = _T("我爱大家");
- const char* cpLog = (const char*)W2A(strLog);
- CFile myFile;
- myFile.Open(_T("test.txt"),CFile::modeCreate|CFile::modeWrite);
- myFile.Write(cpLog,strlen(cpLog));
- myFile.Close();
其实stl也提供了unicode字符的处理,这里的unicode只是两个字节的字符(即unsigned short)。unicode对应的字符串处理比ansi麻烦,相关的类基本前面都带有'w'。如std::wstring,std::wofstream。
下面贴两段代码来实现输出unicode到文件中。
1、
- CString mfcstr = _T("大家.txt");
- std::wstring str = L"大家";
- std::wofstream ofile(mfcstr.GetBuffer(mfcstr.GetLength()));
- ofile.imbue(std::locale("chs")); 设置输出流的imbue属性很重要
- ofile.write(str.c_str(),str.length());
- ofile.write(L"/r/n",2);
- ofile.write(mfcstr.GetBuffer(mfcstr.GetLength()),mfcstr.GetLength());
- ofile<<L"我爱她"<<endl;
- ofile.close();
要注意第四句,如果没有设置第四句,是不能把中文输出到文件中的。
2、设置全局的locale,输出中文到文件会出错,可能是因为没有设置好本地化的东西。
- locale &loc=locale::global(locale(locale(),"",LC_CTYPE));
- ofstream ofs("ofs.txt");
- wofstream wofs(L"wofs测试.txt");
- locale::global(loc);
- ofs<<"test测试"<<1234<<endl;
- wofs<<L"Another test还是测试"<<1234<<endl;
在读取这些文件时,首先要设置好locale,然后再打开文件来读取数据。如:
- std::wstring str = L"大家.txt";
- wstring strLine;
- locale loc("chs");
- wifstream in;
- in.imbue(loc); //关键
- in.open(str.c_str());
- if (!in.is_open())
- {
- AfxMessageBox(L"can't open the file");
- return ;
- }
- while (in>>strLine)
- {
- CString mfcstr(strLine.c_str());
- AfxMessageBox(mfcstr);
- }
- in.close();