C++ 获取目录下具有指定后缀名的所有文件名_linux

 

/************************************************************
 * Description:
 *     获取dir目录下具有制定后缀名字的所有文件名,
 * parameter:
 *     src_dir:目录路径,例如 "../test"
 *     ext:后缀名,例如".jpg"
 * return;
 *     vector<string>:包含文件名的数组,
 * ***********************************************************/
vector<string> GetFiles(const char *src_dir, const char *ext)
{
    vector<string> result;
    string directory(src_dir);
    string m_ext(ext);
    //printf("ext length:%d\n",m_ext.length());

    // 打开目录, DIR是类似目录句柄的东西
    DIR *dir = opendir(src_dir);
    if ( dir == NULL )
    {
        printf("[ERROR] %s is not a directory or not exist!", src_dir);
        return result;
    }

    // dirent会存储文件的各种属性
    struct dirent* d_ent = NULL;

    // linux每个目录下面都有一个"."和".."要把这两个都去掉
    char dot[3] = ".";
    char dotdot[6] = "..";

    // 一行一行的读目录下的东西,这个东西的属性放到dirent的变量中
    while ( (d_ent = readdir(dir)) != NULL )
    {
        // 忽略 "." 和 ".."
        if ( (strcmp(d_ent->d_name, dot) != 0) && (strcmp(d_ent->d_name, dotdot) != 0) )
        {
            // d_type可以看到当前的东西的类型,DT_DIR代表当前都到的是目录,在usr/include/dirent.h中定义的
            if ( d_ent->d_type != DT_DIR)
            {
                string d_name(d_ent->d_name);
                //printf("%s\n",d_ent->d_name);
                if (strcmp(d_name.c_str () + d_name.length () - m_ext.length(), m_ext.c_str ()) == 0)
                {
                    // 构建绝对路径
                    //string absolutePath = directory + string("/") + string(d_ent->d_name);
                    // 如果传入的目录最后是/--> 例如"a/b/", 那么后面直接链接文件名
                    //if (directory[directory.length()-1] == '/')
                    //    absolutePath = directory + string(d_ent->d_name);
                    //result.push_back(absolutePath);
                    result.push_back(string(d_ent->d_name));
                }
            }
        }
    }

    // sort the returned files
    sort(result.begin(), result.end());

    closedir(dir);
    return result;
}

 

  • 2
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

陈 洪 伟

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值