加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c++ scandir 按顺序读取文件目录

发布时间:2020-12-16 07:18:44 所属栏目:百科 来源:网络整理
导读:参考博客: linux 系统获得当前文件夹下存在的所有文件 scandir函数和struct dirent **namelist结构体 scandir目录筛选出所有.c的文件,高手帮忙,谢谢!?[问题点数:40分] c++按顺序读取目录内文件 C语言alphasort()函数:依字母顺序排序目录结构 ? 这四篇

参考博客:

linux 系统获得当前文件夹下存在的所有文件 scandir函数和struct dirent **namelist结构体

scandir目录筛选出所有.c的文件,高手帮忙,谢谢!?[问题点数:40分]

c++按顺序读取目录内文件

C语言alphasort()函数:依字母顺序排序目录结构

?

这四篇讲的都差不多,也比较短,看一遍就ok

过滤器的实现脱离了主函数的,显得精简,函数会先过滤在排序:

下面是我结合我的工程做的一个简单模拟,如果不用过滤器的话,把第三个参数设0,对于返回列表要手动判断是目录还是文件:

#include <dirent.h>
#include <string>
#include <iostream>
#include <unistd.h>

using namespace std;

int fileNameFilter(const struct dirent *cur)
{
    std::string str(cur->d_name);
    if (str.find(".jpg") != std::string::npos)
    {
        return 1;
    }
    return 0;
}

int main()
{
    while(1)
    {
        struct dirent **namelist;
        int n = scandir(".",&namelist,fileNameFilter,alphasort);

        if(n < 0)
            cerr << "memery error " << endl;
        else 
            cout << "total number is: " << n << endl;
            
        for( int i = 0; i < n; i++)
        {
            // /* skip . && .. */
            // if(namelist[i]->d_name[0] == ‘.‘)
            //     continue;

            cout<<namelist[i]->d_name<<endl;
            free(namelist[i]);
        }
        free(namelist);
        sleep(5);
    }

    return 0;
}

?

可以看到文件确实按照升序排列了

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读