scandir按文件名升序获取满足条件的文件名

如果用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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值