C++遍历文件夹文件时出现std::string构造函数匹配错误求助
解决std::filesystem路径转字符串的编译错误
错误根源
代码中std::string curr_path(file.path());报错,是因为file.path()返回的是std::filesystem::path类型,C++标准并未提供std::string直接接收该类型的构造函数,导致参数列表不匹配。
直接修复方案
将该行代码修改为:
std::string curr_path = file.path().string();
调用std::filesystem::path的string()成员方法,即可将路径转换为std::string类型。
优化后的完整代码
考虑到跨平台兼容性和代码简洁性,推荐使用std::filesystem的原生方法处理路径,避免手动切割字符串:
#include <filesystem> #include <vector> #include <string> #include <algorithm> #include <iostream> #include <cctype> namespace fs = std::filesystem; void GetAllImgInDir(const std::string &directory_path, std::vector<std::string> &PathFrames) { PathFrames.clear(); for (const auto& file : fs::recursive_directory_iterator(directory_path)) { // 跳过非文件项(如子目录) if (!file.is_regular_file()) continue; const fs::path& file_path = file.path(); std::string ext = file_path.extension().string(); // 统一转为小写,兼容大小写不同的扩展名(如.PNG/.png) std::transform(ext.begin(), ext.end(), ext.begin(), [](unsigned char c) { return std::tolower(c); }); if (ext == ".bmp" || ext == ".jpeg" || ext == ".jpg" || ext == ".png") { // 直接获取文件名,无需手动处理路径分隔符 std::string base_filename = file_path.filename().string(); std::cout << base_filename << std::endl; PathFrames.push_back(base_filename); } } std::sort(PathFrames.begin(), PathFrames.end()); }
优化细节说明
- 增加
is_regular_file()判断:避免将子目录误识别为文件 - 使用
extension()获取扩展名:比手动切割字符串更可靠,自动处理无扩展名的文件 - 扩展名转小写:兼容不同平台下的扩展名大小写差异
- 使用
filename()获取文件名:自动适配Windows/ Linux的路径分隔符,无需手动处理/或\
内容的提问来源于stack exchange,提问作者Cosmo
相关产品推荐
相关产品推荐

