c++ - Need help recursively creating a directory tree using the Boost Property Tree library and XML -
i've created xml file represents directory layout project. looks this:
<folder> <folder> <name>src</name> <file> <name>main.cpp</name> </file> </folder> <file> <name>makefile</name> </file> <file> <name>readme.md</name> </file> </folder>
i'm using boost property tree (boost::property_tree::ptree
) parse, represent, , create directory (the program i'm trying write command line tool generates empty c++ projects). i'm trying write function create directory recursively, i've never used library before, running few mental blocks, , feel i'm going wrong. if has used library before , can give me few pointers code, i'd appreciate it. here's have far:
static void create_directory_tree(std::string &root_name, boost::property_tree::ptree &directory_tree) { // create root folder. boost::filesystem::create_directory(root_name); (auto &tree_value : directory_tree.get_child("folder")) { // if child file, create empty file // name attribute. if (tree_value.first == "file") { std::ofstream file(tree_value.second.get<std::string>("name")); file << std::flush; file.close(); } // if child folder, call function again // folder root. don't understand data // structure enough know how access // second parameter. else if (tree_value.first == "folder") { create_directory_tree(tree_value.second.get<std::string>("name"), /* ??? */) } // if it's not file or folder, something's wrong xml file. else { throw std::runtime_error(""); } } }
it's not clear me you're asking.
i hope take on helps:
#include <boost/property_tree/ptree.hpp> #include <boost/property_tree/xml_parser.hpp> #include <boost/filesystem.hpp> #include <iostream> using namespace boost::property_tree; namespace fs = boost::filesystem; namespace project_definition { void apply(ptree const& def, fs::path const& rootfolder) { (auto node : def) { if ("folder" == node.first) { fs::path = rootfolder / node.second.get<std::string>("name"); fs::create_directories(where); apply(node.second, where); } if ("file" == node.first) { std::ofstream((rootfolder / node.second.get<std::string>("name")).native(), std::ios::trunc); } } } } int main() { ptree projdef; read_xml("input.txt", projdef); try { project_definition::apply(projdef, "./rootfolder/"); } catch(std::exception const& e) { std::cerr << e.what() << "\n"; } }
with input.txt
of
<folder> <name>project</name> <folder> <name>src</name> <file><name>main.cpp</name></file> </folder> <file><name>makefile</name></file> <file><name>readme.md</name></file> </folder>
creates structure:
./rootfolder ./rootfolder/project ./rootfolder/project/readme.md ./rootfolder/project/src ./rootfolder/project/src/main.cpp ./rootfolder/project/makefile
Comments
Post a Comment