任务很明确,直接上代码。
#include <iostream>
#include <dirent.h>
bool get_filelist_from_dir(std::string _path, std::vector<std::string>& _files)
{
DIR* dir;
dir = opendir(_path.c_str());
struct dirent* ptr;
std::vector<std::string> file;
while((ptr = readdir(dir)) != NULL)
{
if(ptr->d_name[0] == '.') {continue;}
file.push_back(ptr->d_name);
}
closedir(dir);
sort(file.begin(), file.end());
_files = file;
}
其中需要注意的一点是:
struct dirent 结构体对象读出来的文件名是按照dir->d_off来排序的,所以直接得到的文件名称是乱序的,如果我们希望按照文件名称排序,则必须要在文件名称读出来之后自己进行一次排序。具体解释请参考 文件名乱序的原因,感谢博主的分享。

本文介绍了一个使用C++实现的从指定目录中获取所有文件列表,并对其进行排序的方法。通过遍历目录并利用dirent结构体读取每个文件名,然后将文件名存储到std::vector容器中,最后对容器进行排序,确保文件名按字母顺序排列。
341

被折叠的 条评论
为什么被折叠?



