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");
相关推荐
clint4561 天前
C++进阶(1)——前景提要
c++
夜悊1 天前
C++代码示例:进制数简单生成工具
c++
郝学胜_神的一滴1 天前
CMake 021: IF 条件判据详诠
c++·cmake
_wyt0012 天前
洛谷 B3930 [GESP202312 五级] 烹饪问题 题解
c++·gesp
通信小呆呆2 天前
当算法有了“五感”:多模态数据融合如何向人体感官协同学习?
人工智能·学习·算法·机器学习·机器人
H__Rick2 天前
自动对焦学习-3
人工智能·学习·计算机视觉
Daisy Lee2 天前
量化学习-第1章-什么是量化金融
学习·金融·datawhale
Alsn862 天前
等待学习-学习目录:Docker 容器安全攻防
学习·安全·docker
玖玥拾2 天前
C/C++ 数据结构(七)栈、容器适配器
c语言·数据结构·c++··容器适配器
YM52e2 天前
买菜计算器小应用 - HarmonyOS ArkUI 开发实战-PC版本
学习·华为·harmonyos·鸿蒙·鸿蒙系统