c++学习:容器list实战(获取目录返回容器list)

新建一个dir.h,声明dir类

复制代码
#ifndef DIR_H
#define DIR_H

#include <sys/types.h>
 #include <dirent.h>
#include <stdio.h>
#include <string.h>

#include <iostream>
#include <list>

class Dir
{
public:
    Dir();

    static std::list<std::string> entryList(const char *dirPath, const char *filter);
};

#endif // DIR_H

新建一个dir.cpp,定义dir类

复制代码
#include "dir.h"


Dir::Dir()
{

}

std::list<std::string> Dir::entryList(const char *dirPath, const char *filter)
{
    std::list<std::string> list;

     DIR * fp = opendir(dirPath);
     if(fp == NULL)
     {
         perror("opendir error");
         return list;
     }

     while(1)
     {
        struct dirent * info = readdir(fp);
        if(info == NULL)
        {
            break;
        }

        if(info->d_type == DT_REG && info->d_name[0] != '.' &&
                strstr(info->d_name,filter)!=NULL)
        {
            //获取文件名
            char text[1024] = {0};

            if(dirPath[strlen(dirPath)-1] == '/')
            {
                sprintf(text,"%s%s",dirPath,info->d_name);
            }
            else{
                sprintf(text,"%s/%s",dirPath,info->d_name);
            }

            //存储到 链表容器中
            list.push_back(text);
        }
     }

     return list;
}

调用方法

复制代码
//返回当前目录下以txt结尾的文件
std::list<string> list = Dir::entryList("./",".txt");
相关推荐
芷栀夏3 小时前
Java教育平台实战复盘:课程、考试与学习行为分析系统设计
java·开发语言·学习
从零开始的代码生活_3 小时前
C++ 多态详解:虚函数、动态绑定、抽象类与虚表原理
开发语言·c++·后端·学习·算法
大彼方..4 小时前
C++ STL Vector 深度剖析:从内存管理到性能优化
开发语言·c++
炸薯条!4 小时前
从零开始学C++ (内存管理)
java·jvm·c++
执笔论英雄5 小时前
【大模型推理 】 vllm kvconnet 学习
学习·vllm
·醉挽清风·6 小时前
学习笔记—算法—算法题
笔记·学习·算法
cpp_25016 小时前
P6625 [省选联考 2020 B 卷] 卡牌游戏
数据结构·c++·算法·前缀和·贪心·洛谷题解·省选
a1117766 小时前
机器人导航入门指南(从 0 到 1)
笔记·学习·slam
范什么特西7 小时前
每日学习-01
学习
旺仔丶歪歪乐7 小时前
英语启蒙APP分级体系拆解:本土课标分级与海外原版分级有什么区别
人工智能·学习·web app