如果用readdir扫描目录,文件名是按照索引排序的,会显得凌乱。在某些情况下我们需要文件名的顺序排列,那么久需要用scandir了。
按文件名升序排列的获取如下所示:
#include <iostream>
#include <vector>
#include <string.h>
#include <stdio.h> //标准输入输出
#include <unistd.h> //各种系统调用
#include <dirent.h> //与目录有关的操作
#include <string.h> //与字符串处理有关的函数
#include <sys/stat.h> //与文件状态有关
#include <sys/types.h> //linux系统自定义的类型
using namespace std;
static int filter_fn(const struct dirent *ent)
{
if (ent->d_type != DT_REG)
return 0;
const char *ext = strrchr(ent->d_name, '.');
if (!ext)
{
return 0;
}
return strcmp(ext, ".xml") == 0;
}
static int name_sort(const struct dirent **file1, const struct dirent **file2)
{
return strcmp((*file2)->d_name, (*file1)->d_name);
}
bool scan_dir(const char *cfg_path, vector<string> &filenames, string &errmsg)
{
struct dirent **namelist; // struct dirent * namelist[];
int n = scandir(cfg_path, &namelist, filter_fn, name_sort);
if (n < 0)
{
char buf[4096];
snprintf(buf, sizeof buf, "扫描目录错误:%s", strerror(errno));
errmsg.assign(buf);
return false;
}
for (int i = 0; i < n; i++)
{
filenames.emplace_back(string(namelist[i]->d_name));
cout << namelist[i]->d_name << endl;
free(namelist[i]);
}
free(namelist);
return true;
}
int main(int argc, char **argv)
{
vector<string> filenames;
string errmsg;
if (false == scan_dir("./dd", filenames, errmsg)) {
cout << errmsg << endl;
}
return 0;
}