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");
相关推荐
青少儿编程课堂10 分钟前
蓝桥杯·全国青少年信息素养大赛·电子学会Python/C++考级:Bellman-Ford与SPFA含负权最短路及负环检测全解析
c++·python·算法·bfs·信息学竞赛
叼烟扛炮16 分钟前
[LangChain] 学习笔记(03):打破失忆症——对话机制与上下文管理
java·前端·javascript·笔记·学习·langchain
旖旎夜光26 分钟前
【C++ 基础入门】类和对象(下):初始化列表、static 成员、友元与内部类
c++·笔记·学习
j7~38 分钟前
【C++ 八股文】(篇四)C++11 新特性
开发语言·c++·面试·c++11·八股文
LONGZHIQIN1 小时前
STM32学习笔记
笔记·stm32·学习·arm
eggwyw1 小时前
C++中大括号的用法合集
开发语言·c++
xiaoye-duck1 小时前
《C++ 项目:手写大模型接入 SDK》本地 Ollama 部署与适配
开发语言·网络·c++·语言模型
redtank20001 小时前
纯血鸿蒙小工具三件套实测:弹幕手持、爱记录与仓库管理软件
学习·华为·智能手机·harmonyos
§ꦿCFོ༉1 小时前
嵌入式八股文—C语言入门学习(二)
c语言·学习·嵌入式·编程语言
octopus_c1 小时前
STL 之 string:auto 与范围 for、常用接口、模拟实现与深浅拷贝
开发语言·c++·算法