如何使用 C++ filesystem 递归目录?
#include <Windows.h>
#include <iostream>
#include <string>
#include <fstream>
#include <filesystem>
std::string w2a(const std::wstring& utf8)
{
int buffSize = WideCharToMultiByte(CP_UTF8, NULL, utf8.c_str(), -1, NULL, NULL, NULL, FALSE);
char* bf = new char[buffSize + 1];
memset(bf, 0, buffSize + 1);
WideCharToMultiByte(CP_UTF8, NULL, utf8.c_str(), -1, bf, buffSize, NULL, FALSE);
std::string result(bf);
delete[] bf;
bf = nullptr;
return result;
}
struct TreeNode
{
TreeNode(const std::filesystem::path newPath) {
path = newPath;
}
void addChild(std::shared_ptr<TreeNode> child) {
children.push_back(child);
}
std::string name() {
return w2a(path.native());
}
std::vector<std::shared_ptr<TreeNode>> data() {
return children;
}
std::filesystem::path path;
std::vector<std::shared_ptr<TreeNode>> children;
};
// none member function
void recursion(const std::filesystem::path path, std::shared_ptr<TreeNode>& node) {
for (auto& p : std::filesystem::directory_iterator(path)) {
if (p.is_directory()) {
auto newNode = std::make_shared<TreeNode>(p.path());
node->addChild(newNode);
recursion(p.path(), newNode);
std::wcout << p.path().native() << '\n';
}
}
}
void recursion_node(std::fstream& fs, std::shared_ptr<TreeNode>& node, int depth) {
std::string str = "";
for (int i = 0; i < depth; i++) {
str += "\t";
}
fs << node->name() << std::endl;
depth++;
for (auto& v : node->data()) {
fs << str;
recursion_node(fs, v, depth);
}
}
void print(const std::string& filename, std::shared_ptr<TreeNode>& root) {
std::fstream fs(filename, std::fstream::trunc | std::fstream::out);
if (!fs.is_open()) {
std::cout << "failed to open " << filename << std::endl;
return;
}
recursion_node(fs, root, 1);
}
int main()
{
auto rc = std::filesystem::path(R"(A:\Temp\root)");
auto root = std::make_shared<TreeNode>(rc);
recursion(rc, root);
print("aaaa4.txt", root);
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)