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");
相关推荐
蜕变的土豆14 分钟前
工业监控RTSP取流-实践指南
c++·视频
进化中的刀盾兽15 分钟前
从零实现 C++ Json-Rpc(八):补齐 detail.hpp——JSON 封装与请求 ID 生成
c++·rpc
陈年老古董19 分钟前
Hive 分区表学习笔记:语法、操作、二级分区与动态分区
hive·笔记·学习
li星野32 分钟前
The 3 Common Tenses — Notes & Supplements
学习
小弥儿33 分钟前
GitHub今日热榜 | 2026-10-09:PS5 移植登顶,AI 创作工具占三席
人工智能·学习·开源·github
longlongzihan34 分钟前
LeetCode 41. 缺失的第一个正数:从基础解法到原地哈希
c++·算法·leetcode
全栈道1 小时前
AI 时代,软件开发应该如何学习
人工智能·学习
存在morning1 小时前
【OLAP 学习笔记】Doris:数据湖之上的分析查询引擎
笔记·学习
代码山河1 小时前
Java语言特点:跨平台、面向对象、安全性详解
java·学习·架构·教程·面向对象·项目
Lhan.zzZ1 小时前
Qt/QML:业务记录单展示、签名确认与 PDF 导出开发
c++·qt·pdf