为何std::filesystem::copy()抛出"generic: 2"错误?
问题分析与修复方案
你遇到的generic:2错误通常对应文件或目录不存在的问题,结合代码来看,主要有以下几个问题需要修复:
1. 成员函数调用错误
main函数里直接用类名backup调用非静态成员函数fetch_files,这是语法错误,必须通过实例化的对象调用:
// 错误写法 std::cout << backup.fetch_files("~/Desktop/backup_source") << std::endl; // 正确写法 std::cout << example_backup.fetch_files("~/Desktop/backup_source") << std::endl;
2. ~路径未被解析
std::filesystem不会自动解析shell中的~(家目录符号),直接使用会导致程序找不到对应路径。需要手动获取家目录并拼接路径:
// 获取系统家目录 std::string home_dir = std::getenv("HOME"); // 拼接目标路径 backup example_backup(home_dir + "/Desktop/backup_destination"); // 拼接源路径 example_backup.fetch_files(home_dir + "/Desktop/backup_source");
3. 确保目标目录存在
如果目标目录不存在,fs::copy可能执行失败,建议在复制前先创建目标目录:
在fetch_files函数中添加目录创建逻辑:
// 创建目标目录(含父目录),忽略已存在的错误 fs::create_directories(location, err); if (err) { return err; }
修复后的完整代码
#include <filesystem> #include <string> #include <iostream> #include <cstdlib> // 用于std::getenv namespace fs = std::filesystem; class backup { private: fs::path location; public: backup(std::string location_str) : location(location_str) {} std::error_code fetch_files(const std::string& src_str) { std::error_code err; fs::path src(src_str); // 先创建目标目录 fs::create_directories(location, err); if (err) { return err; } fs::copy_options copy_opts = fs::copy_options::recursive | fs::copy_options::overwrite_existing | fs::copy_options::copy_symlinks; fs::copy(src, location, copy_opts, err); return err; } }; // 补充分号,原代码遗漏类定义结束分号 int main(int argc, char* argv[]) { std::string home_dir = std::getenv("HOME"); if (home_dir.empty()) { std::cerr << "无法获取家目录" << std::endl; return 1; } backup example_backup(home_dir + "/Desktop/backup_destination"); std::error_code err = example_backup.fetch_files(home_dir + "/Desktop/backup_source"); std::cout << err.message() << " (" << err.value() << ")" << std::endl; return err.value() == 0 ? 0 : 1; }
额外说明
- 原代码中类定义结束时遗漏分号
};,属于语法错误,必须补上。 - 输出错误时建议打印
err.message(),能得到更直观的错误描述,而非仅输出错误码。
内容的提问来源于stack exchange,提问作者huetrashme0947
相关产品推荐
相关产品推荐

