I want to read a json data from a file in C++ using boost libraries. Using property tree. I am new to programming, very new to c++ and its the first time i use boost library. I had some history in C many years ago. And i have a weeks experience in C++ using SFML library.
Below is my template code loads a file, reads data and if fails give an error. I want to change my error handling a bit different way. 1. if i cant open the mentioned file because it doesn't exist I want to create a blank file named accordingly. 2. But if some other error happens but the file exists I don't want to accidentally delete the file and create new one (erasing the data).
I guess it will be something like
catch (const std::exception& e)
{
if (e.type == std::exception::filenotfound()) //whatever function i need
{
boost::property_tree::write_json("./data.json", pt);
}
else
{
std::cout << e.what() << std::endl;
}
}
So I want to create the file only if it genuinely doesn't exist but if somehow corrupted, missing data i look for or some unimaginable other error happens I don't want to delete it. Here is my template (without the implementation of what i want)
#include <iostream>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>
int main()
{
boost::property_tree::ptree pt;
try
{
boost::property_tree::read_json("./data.json", pt);
}
catch (const std::exception& e)
{
std::cout << e.what() << std::endl;
}
std::cout << pt.get<std::string>("test_name","default") << std::endl;
return 0;
}
How exactly I should write this code. I searched the internet for 2 hours but I couldn't find anything i want. (Or at least I didn't notice) And I am not experienced enough to decode original library documentations. They feel like encrypted to me so I look for samples instead.