stl 输出unicode到文件中

在VS2008中,如果项目设置了unicode字符集,把中文输出到文件中经常会遇到错误。

在MFC项目中,可以使用以下语句来实现unicode到多字节字符的转换:

  1. USES_CONVERSION;
  2. CString strLog = _T("我爱大家");
  3. const char*   cpLog   =   (const char*)W2A(strLog);
  4. CFile myFile;
  5. myFile.Open(_T("test.txt"),CFile::modeCreate|CFile::modeWrite);
  6. myFile.Write(cpLog,strlen(cpLog));
  7. myFile.Close();

其实stl也提供了unicode字符的处理,这里的unicode只是两个字节的字符(即unsigned short)。unicode对应的字符串处理比ansi麻烦,相关的类基本前面都带有'w'。如std::wstring,std::wofstream。

下面贴两段代码来实现输出unicode到文件中。

1、

  1. CString mfcstr = _T("大家.txt");
  2. std::wstring   str   =   L"大家"
  3. std::wofstream   ofile(mfcstr.GetBuffer(mfcstr.GetLength()));
  4. ofile.imbue(std::locale("chs"));   设置输出流的imbue属性很重要
  5. ofile.write(str.c_str(),str.length());
  6. ofile.write(L"/r/n",2);
  7. ofile.write(mfcstr.GetBuffer(mfcstr.GetLength()),mfcstr.GetLength());
  8. ofile<<L"我爱她"<<endl;
  9. ofile.close();  

要注意第四句,如果没有设置第四句,是不能把中文输出到文件中的。

 

2、设置全局的locale,输出中文到文件会出错,可能是因为没有设置好本地化的东西。

  1. locale &loc=locale::global(locale(locale(),"",LC_CTYPE));
  2. ofstream ofs("ofs.txt");
  3. wofstream wofs(L"wofs测试.txt");
  4. locale::global(loc);
  5. ofs<<"test测试"<<1234<<endl;
  6. wofs<<L"Another test还是测试"<<1234<<endl;

在读取这些文件时,首先要设置好locale,然后再打开文件来读取数据。如:

  1. std::wstring   str   =   L"大家.txt"
  2.     wstring strLine;
  3.     locale loc("chs"); 
  4.     wifstream in;
  5.     in.imbue(loc);   //关键
  6.     in.open(str.c_str());
  7.     if (!in.is_open())
  8.     {
  9.         AfxMessageBox(L"can't open the file");
  10.         return ;
  11.     }
  12.     while (in>>strLine)
  13.     {
  14.         CString mfcstr(strLine.c_str());
  15.         AfxMessageBox(mfcstr);
  16.     }
  17.     in.close();

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值