文章详情
C++中linux开发获取指定目录下所有指定文件
Posted on 2023-03-01 07:31:28 by 主打一个C++
//函数封装,参数(要遍历的目录,指定后辍名,返回列表)
bool broadcast_server::getFiles(const std::string& _directory, const std::string& _extension, std::vector<std::string>& _list) {
DIR* dir;
struct dirent* ent;
// 打开目录
if ((dir = opendir(_directory.c_str())) != nullptr) {
// 遍历目录
while ((ent = readdir(dir)) != nullptr) {
// 检查是否是文件并且以.php结尾
if (ent->d_type == DT_REG) { // 确保是常规文件
std::string fileName = ent->d_name;
if (fileName.size() > 4 && fileName.substr(fileName.size() - 4) == _extension) {
_list.push_back(fileName);
}
}
}
closedir(dir); // 关闭目录
}
else {
std::cerr << "无法打开目录: " << strerror(errno) << std::endl;
return false;
}
return true;
}
*转载请注明出处:原文链接:https://cpp.vin/page/98.html