使用 C++ filesystem 递归目录

2023-05-16

如何使用 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(使用前将#替换为@)

使用 C++ filesystem 递归目录 的相关文章

  • Converting circular structure to JSON

    在做手机验证码模块 xff0c 遇到一个bug Converting circular span class hljs keyword structure span span class hljs keyword to span JSON
  • Mac root和普通用户切换

    今日 xff0c 老身在用su 命令 xff0c 输入密码之后准备切换至root用户 但不幸得到这个消息 xff1a su Sorry 找到解决方案如下 xff1a span class hljs built in sudo span su

随机推荐