最近有个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";
}
}