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");
相关推荐
小陈phd1 分钟前
多模态大模型学习笔记(二十一)—— 基于 Scaling Law方法 的大模型训练算力估算与 GPU 资源配置
笔记·深度学习·学习·自然语言处理·transformer
丝斯20114 分钟前
AI学习笔记整理(75)——Python学习4
人工智能·笔记·学习
2301_8166512210 分钟前
C++中的享元模式变体
开发语言·c++·算法
m0_5832031313 分钟前
C++中的访问者模式变体
开发语言·c++·算法
小帅学编程15 分钟前
英语学习笔记
java·笔记·学习
AI成长日志16 分钟前
【datawhale】hello agents开源课程学习记录第4章:智能体经典范式构建
学习·开源
EnglishJun18 分钟前
ARM嵌入式学习(七)--- 汇编基础(数据指令、函数调用原理、中断原理)
arm开发·学习
浅念-20 分钟前
C ++ 智能指针
c语言·开发语言·数据结构·c++·经验分享·笔记·算法
今儿敲了吗21 分钟前
python基础学习笔记第七章——文件操作
笔记·python·学习
不染尘.21 分钟前
最小生成树算法
开发语言·数据结构·c++·算法·图论