我诧,这个FS接口怎么这么不好用,居然还进了C++17。可以用auto lambda把不同类型的参数隔离出来复用其他相同代码吧。
#include <filesystem>
#include <fstream>
#include <iostream>
#include <random>
#include <variant>
namespace fs = std::filesystem;
int main() {
std::mt19937 rng(std::random_device{}());
bool recur = (std::uniform_int_distribution<>{}(rng)) & 1;
fs::current_path(fs::temp_directory_path());
fs::create_directories("sandbox/a/b");
fs::create_symlink("a", "sandbox/syma");
std::ofstream("sandbox/file1.txt");
std::ofstream("sandbox/file2.txt");
auto iter = [](auto dir) {
for (auto &p : dir) std::cout << p.path() << std::endl;
};
// Calls lambda directly if it is simple.
if (recur) iter(fs::recursive_directory_iterator("sandbox"));
else iter(fs::directory_iterator("sandbox"));
// Variants visitor to handle more types.
std::variant<fs::recursive_directory_iterator, fs::directory_iterator> dir;
if (recur) dir = fs::recursive_directory_iterator("sandbox");
else dir = fs::directory_iterator("sandbox");
std::visit(iter, dir);
fs::remove_all("sandbox");
return 0;
}
【 在 miui 的大作中提到: 】
: 比如我有一个函数,如果bRecursive为true,则
: namespace fs = std::filesystem;
: foo(const std::string& strPath, const bRecursive)
: ...................
--
修改:ble FROM 104.134.27.*
FROM 104.134.27.*