#include <sstream>
#include <locale>
#include <codecvt>
#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";
}
}
代码使用
读取UTF-16 LE
{
std::wstring wstrCraftIniFile = CSystemTool::GetCraftFile();
try {
FILE* fp = _wfopen(wstrCraftIniFile.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);
for (int i = 0; i < MAX_WORKSTATION_CNT; ++i)
{
std::wstringstream ss;
std::wstring_convert<std::codecvt_utf8<wchar_t>> converter;
wstring key = converter.from_bytes(GetWorkNameKey());
ss << key << L"."<< i;
boost::optional<std::wstring> strVal = pt.get_optional<std::wstring>(ss.str());
std::wstring strName = strVal.get_value_or(std::wstring(L""));
m_vecWorkNames.push_back(strName);
}
}
catch (std::exception e)
{
string err = e.what();
cout << err;
}
}
读取ANSI
try {
boost::filesystem::path file(wstrCraftIniFile);
boost::property_tree::ptree pt;
boost::property_tree::ini_parser::read_ini(file.string(), pt);
for (int i = 0; i < MAX_WORKSTATION_CNT; ++i)
{
std::stringstream ss;
ss << GetWorkNameKey() << "."<< i;
std::string strName = pt.get<std::string>(ss.str(), "");
m_vecWorkNames.push_back(CStringHelper::mbs2wchar(strName));
}
}
catch (std::exception e)
{
string err = e.what();
cout << err;
}