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");
相关推荐
apocelipes21 小时前
常用编程语言和库的正则表达式性能对比
c语言·c++·python·性能优化·golang·开发工具和环境
郝学胜_神的一滴2 天前
CMake 034:生成器表达式:解耦构建时序、精简分支逻辑的终极利器
c++·cmake
见过夏天3 天前
C++ 基础入门完全指南
c++
用户805533698034 天前
不止三件套:QObject 属性系统全关键字与运行时反射!
c++·qt
BadBadBad__AK5 天前
线段树维护区间 k 次方和
c++·数学·算法·stl
卷无止境5 天前
Eigen 库如何借助 OpenMP 加速计算
c++·后端
卷无止境5 天前
OpenMPI、MPICH 与 OpenMP:关系、核心概念与架构全解
c++·后端
郝学胜_神的一滴6 天前
CMake 30:循环语法全解|foreach_while双循环精讲、迭代技巧与实战避坑指南
c++·cmake
卷无止境8 天前
C++ 的Eigen 库全解析
c++
卷无止境8 天前
现代 C++特性大盘点:一门脱胎换骨的老语言
c++·后端