任务很明确,直接上代码。
#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来排序的,所以直接得到的文件名称是乱序的,如果我们希望按照文件名称排序,则必须要在文件名称读出来之后自己进行一次排序。具体解释请参考 文件名乱序的原因,感谢博主的分享。