#include <cassert>
#include <fstream>
#include <iostream>
#include <string>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/xml_parser.hpp>
///An Id contains a location number and an ID.
struct Id
{
Id(const int location = 0, const int id = 0)
: m_location(location), m_id(id) {}
int m_location;
int m_id;
};
std::ostream& operator<<(std::ostream& os,const Id& id)
{
os
<< id.m_location
<< ' ' //Add either a space, tab or newline
<< id.m_id;
return os;
}
std::istream& operator>>(std::istream& is, Id& id)
{
is
>> id.m_location
>> id.m_id;
return is;
}
bool operator==(const Id& lhs, const Id& rhs)
{
return
lhs.m_location == rhs.m_location
&& lhs.m_id == rhs.m_id;
}
struct Person
{
std::string m_name;
Id m_id;
void Load(const std::string &filename)
{
boost::property_tree::ptree t;
boost::property_tree::xml_parser::read_xml(filename,t);
m_name = t.get<std::string>("Person.name");
m_id.m_location = t.get<int>("Person.id.location");
m_id.m_id = t.get<int>("Person.id.id");
}
void Save(const std::string &filename) const
{
boost::property_tree::ptree t;
t.put("Person.name", m_name);
t.put("Person.id.location", m_id.m_location);
t.put("Person.id.id", m_id.m_id);
boost::property_tree::xml_parser::write_xml(filename,t);
}
};
std::ostream& operator<<(std::ostream& os,const Person& p)
{
os << p.m_name
<< ' ' //Add either a space, tab or newline
<< p.m_id;
return os;
}
std::istream& operator>>(std::istream& is, Person& p)
{
is
>> p.m_name
>> p.m_id;
return is;
}
int main()
{
//Create a Person and save it to file
{
Person p;
p.m_name = "Bilderbikkel";
p.m_id = Id(314,42);
std::ofstream f("tmp.txt");
f << p;
}
//Load a Person from file and check it is the same
{
std::ifstream f("tmp.txt");
Person p;
f >> p;
assert(p.m_name == "Bilderbikkel");
assert(p.m_id == Id(314,42));
}
//Display tmp.txt
{
std::cout << "Displaying tmp.txt:\n";
std::ifstream f("tmp.txt");
while(!f.eof())
{
std::string s;
std::getline(f,s);
std::cout << s << '\n';
}
}
//Create a Person and save it to XML file
{
Person p;
p.m_name = "Bilderbikkel";
p.m_id = Id(314,42);
p.Save("tmp.xml");
}
//Load a Person from XML file and check it is the same
{
Person p;
p.Load("tmp.xml");
assert(p.m_name == "Bilderbikkel");
assert(p.m_id == Id(314,42));
}
//Display tmp.xml
{
std::cout << "Displaying tmp.xml:\n";
std::ifstream f("tmp.xml");
while(!f.eof())
{
std::string s;
std::getline(f,s);
std::cout << s << '\n';
}
}
}
|