我已经创建了一个 XML 文件来表示项目的目录布局。它看起来像这样:
<folder>
<folder>
<name>src</name>
<file>
<name>main.cpp</name>
</file>
</folder>
<file>
<name>Makefile</name>
</file>
<file>
<name>README.md</name>
</file>
</folder>
我正在使用 Boost 属性树 (boost::property_tree::ptree
) 来解析、表示和创建目录(我正在尝试编写的程序是一个命令行工具生成空的 C++ 项目)。我正在尝试编写一个递归创建目录的函数,但我以前从未使用过这个库,目前遇到了一些心理障碍,感觉我做错了。如果有人以前使用过这个库并且可以用我的代码给我一些建议,我将不胜感激。这是我到目前为止所拥有的:
static void create_directory_tree(std::string &root_name,
boost::property_tree::ptree &directory_tree)
{
// Create the root folder.
boost::filesystem::create_directory(root_name);
for (auto &tree_value : directory_tree.get_child("folder"))
{
// If the child is a file, create an empty file with the
// name attribute.
if (tree_value.first == "file")
{
std::ofstream file(tree_value.second.get<std::string>("name"));
file << std::flush;
file.close();
}
// If the child is a folder, call this function again with
// the folder as the root. I don't understand the data
// structure enough to know how to access this for my
// second parameter.
else if (tree_value.first == "folder")
{
create_directory_tree(tree_value.second.get<std::string>("name"), /* ??? */)
}
// If it's not a file or folder, something's wrong with the XML file.
else
{
throw std::runtime_error("");
}
}
}
最佳答案
我不太清楚你在问什么。
希望我的看法对您有所帮助:
#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) {
for (auto node : def) {
if ("folder" == node.first) {
fs::path where = 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";
}
}
input.txt
为
<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>
创建一个结构:
./rootfolder
./rootfolder/project
./rootfolder/project/README.md
./rootfolder/project/src
./rootfolder/project/src/main.cpp
./rootfolder/project/Makefile
关于c++ - 需要帮助使用 Boost Property Tree 库和 XML 递归创建目录树,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30251529/