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");
相关推荐
欧特克_Glodon11 小时前
OpenCV计算机视觉开发入门与实践<七>:OpenCV 界面编程之窗口
c++·人工智能·opencv·计算机视觉
郝学胜_神的一滴12 小时前
C++20 高级编程 002:夯实现代C++底层基本功
c++·编程语言
风吹心凉12 小时前
ROS2核心概念
学习
老赵的博客12 小时前
可维护性 可扩展性 可复用性
开发语言·c++
jaysee-sjc12 小时前
【JavaWeb】Tlias智能学习辅助系统|后端Web实战(登录认证)
java·开发语言·前端·学习·mybatis
MartinYeung513 小时前
[论文学习]AdInject:通过广告投放对Web代理发起真实世界黑盒攻击
前端·学习
runafterhit13 小时前
【学习地图】Linux学习类 · 文章索引
linux·运维·学习
不正经学生13 小时前
C语言大小端字节序:内存里字节的排列顺序
c语言·开发语言·arm开发·c++·算法·c#
黑泽明*13 小时前
LVS-Keepalived-全解析
服务器·开发语言·笔记·学习·php
大模型码小白14 小时前
AI安全前沿:AI大模型安全防护的前沿技术
java·网络·人工智能·python·深度学习·学习·安全