限于单个函数。
chatgpt写的两种风格的递归目录复制。夹杂的字符串打印很扎眼。
错误码方式:
#include <iostream>
#include <filesystem>
namespace fs = std::filesystem;
void RecursiveCopy(const fs::path& srcDir, const fs::path& dstDir) {
std::error_code ec;
// 检查并创建目标目录
fs::create_directories(dstDir, ec);
if (ec) {
std::wcerr << L"Error creating directory " << dstDir << L": " << ec.message() << std::endl;
return;
}
// 遍历源目录中的每个文件和子目录
for (const auto& entry : fs::recursive_directory_iterator(srcDir, ec)) {
if (ec) {
std::wcerr << L"Error iterating directory " << srcDir << L": " << ec.message() << std::endl;
break;
}
// 构造对应的目标路径
const fs::path destPath = dstDir / fs::relative(entry.path(), srcDir, ec);
if (ec) {
std::wcerr << L"Error calculating relative path for " << entry.path() << L": " << ec.message() << std::endl;
break;
}
if (fs::is_directory(entry.path(), ec)) {
if (ec) {
std::wcerr << L"Error checking if path is directory " << entry.path() << L": " << ec.message() << std::endl;
break;
}
// 确保目标目录存在
fs::create_directories(destPath, ec);
if (ec) {
std::wcerr << L"Error creating directory " << destPath << L": " << ec.message() << std::endl;
break;
}
} else if (fs::is_regular_file(entry.path(), ec)) {
if (ec) {
std::wcerr << L"Error checking if path is file " << entry.path() << L": " << ec.message() << std::endl;
break;
}
// 复制文件到目标目录,覆盖已有文件
fs::copy_file(entry.path(), destPath, fs::copy_options::overwrite_existing, ec);
if (ec) {
std::wcerr << L"Error copying file " << entry.path() << L" to " << destPath << L": " << ec.message() << std::endl;
break;
}
}
}
}
int main() {
fs::path srcDir = L"C:\\path\\to\\source\\directory";
fs::path dstDir = L"C:\\path\\to\\destination\\directory";
RecursiveCopy(srcDir, dstDir);
return 0;
}
异常方式:
#include <iostream>
#include <filesystem>
namespace fs = std::filesystem;
void RecursiveCopy(const fs::path& srcDir, const fs::path& dstDir) {
try {
// 检查并创建目标目录
fs::create_directories(dstDir);
// 遍历源目录中的每个文件和子目录
for (const auto& entry : fs::recursive_directory_iterator(srcDir)) {
// 构造对应的目标路径
const fs::path destPath = dstDir / fs::relative(entry.path(), srcDir);
if (fs::is_directory(entry.path())) {
// 确保目标目录存在
fs::create_directories(destPath);
} else if (fs::is_regular_file(entry.path())) {
// 复制文件到目标目录,覆盖已有文件
fs::copy_file(entry.path(), destPath, fs::copy_options::overwrite_existing);
}
}
} catch (const fs::filesystem_error& e) {
std::wcerr << L"Filesystem error: " << e.what() << std::endl;
} catch (const std::exception& e) {
std::cerr << "Error: " << e.what() << std::endl;
}
}
--
FROM 114.241.228.*