默认是这样的
#include <filesystem>
#include <iostream>
#include <expected>
namespace fs = std::filesystem;
std::expected<void, std::string> copy_directory(const fs::path& src, const fs::path& dst) {
try {
// 检查源目录是否存在
if (!fs::exists(src) || !fs::is_directory(src)) {
return std::unexpected("Source directory does not exist or is not a directory.");
}
// 创建目标目录
if (fs::exists(dst)) {
return std::unexpected("Destination directory already exists.");
}
fs::create_directories(dst);
// 递归复制
for (const auto& entry : fs::recursive_directory_iterator(src)) {
const auto& path = entry.path();
auto relative_path = fs::relative(path, src);
fs::path dst_path = dst / relative_path;
if (fs::is_directory(path)) {
fs::create_directories(dst_path);
} else if (fs::is_regular_file(path)) {
fs::copy_file(path, dst_path);
} else {
return std::unexpected("Unsupported file type encountered.");
}
}
} catch (const fs::filesystem_error& e) {
return std::unexpected(e.what());
}
return {}; // 成功,返回一个空的 std::expected<void, std::string>
}
int main() {
auto result = copy_directory("source_directory", "destination_directory");
if (!result.has_value()) {
std::cerr << "Error: " << result.error() << '\n';
} else {
std::cout << "Directory copied successfully.\n";
}
return 0;
}
【 在 milksea 的大作中提到: 】
: 用 expected 估计能好点,配合类似 rust 的 ? 语法就更好了
--
FROM 114.241.228.*