C++流读取Unicode(UTF-16)格式ini文件

      最近有个Windows平台的项目需要读取并修改ini配置文件。可是本人厌倦了用Win API来写代码,如果用GetPrivateProfileString和WritePrivateProfileString之类API是否对得起自己的造轮子精神呢?呵呵......

      本来打算用C++ std::wifstream流来读取Unicode文件,可是本人电脑是Win7中文,默认环境语言代码页是.936,这样根本解析不了带有LE BOM(FF FE)的UTF-16文件。而且std::locale()也设置不了UTF-16的解析格式。没有办法只有祭出C来。别忘了,C标准库中还有_wfopen函数可以设置解析文件的格式。采用曲线救国的方式也可以达成目的。我们将wfopen打开的文件读入字符流std::wstringstream中,然后用boost::property_tree::wptree来解析这个流就行了。记住包含头文件#include <sstream>、 #include <boost/property_tree/ini_parser.hpp>。废话不多说,直接上关键代码:

      

void HandleIniUTF16()
{
    std::wstring szFile = L"Chinese(Simplified).txt";
    std::locale old = std::locale::global(std::locale(""));

    try
    {
        FILE* fp = _wfopen(szFile.c_str(), L"r, ccs=UTF-16LE");
        std::wstringstream wss;

        wchar_t str[1024] = {0};
        while (fgetws(str, 1024, fp) != NULL)
        {

            wss << str;
        }

        fclose(fp);
        boost::property_tree::wptree pt;
        boost::property_tree::read_ini(wss, pt);
        boost::optional<std::wstring> strVal = pt.get_optional<std::wstring>(L"Person.Name");
        std::wstring ret = strVal.get_value_or(std::wstring(L"no value"));
        pt.put(L"Person.Name", L"elvis");
        write_ini_ex(wss, pt);
     fp = _wfopen(szFile.c_str(), L"wt, ccs=UTF-16LE");
    fputws(wss.str().c_str(), fp);
     fclose(fp);
    }
    catch (boost::property_tree::ini_parser_error& ex)
    {
        AfxMessageBox(ex.what());
    }catch (std::exception& ex)
    {
        AfxMessageBox(ex.what());
    }

    std::locale::global(old);
}

 

 

      自定义函数如下:

      

static void write_ini_ex(std::wstringstream& wss, const boost::property_tree::wptree& pt)
{
	wss.str(L""); wss.clear();

	for (BOOST_AUTO(pos,pt.begin()); pos!=pt.end(); ++pos)
	{
		std::wstring szSec = pos->first;
		wss << L'[' << szSec << L']' << L"\n";
		if (!pos->second.empty())
		{
			for (BOOST_AUTO(it,pos->second.begin()); it!=pos->second.end(); ++it)
			{
				std::wstring szKey = it->first;
				wss << szKey << L'=' ;
				std::wstring szVal = it->second.data();
				if (!szVal.empty())
				{
					wss << szVal;
				}

				wss << L"\n";
			}
		}

		wss << L"\n";
	}
}

 

 

 

     

  

转载于:https://www.cnblogs.com/ElvisZheng/p/5676244.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值