C++ 获取指定目录下的所有文件名称

参考这个大佬的博客:【C语言】S_ISDIR S_ISREG等常见的几个宏
1、stat结构体

struct stat {
        mode_t     st_mode;       //文件对应的模式,文件,目录等
        ino_t      st_ino;        //inode节点号
        dev_t      st_dev;        //设备号码
        dev_t      st_rdev;       //特殊设备号码
        nlink_t    st_nlink;      //文件的连接数
        uid_t      st_uid;        //文件所有者
        gid_t      st_gid;        //文件所有者对应的组
        off_t      st_size;       //普通文件,对应的文件字节数
        time_t     st_atime;      //文件最后被访问的时间
        time_t     st_mtime;      //文件内容最后被修改的时间
        time_t     st_ctime;      //文件状态改变时间
        blksize_t st_blksize;     //文件内容对应的块大小
        blkcnt_t   st_blocks;     //伟建内容对应的块数量
};

2、stat函数

int stat(const char *path, struct stat *struct_stat);
	第一个参数都是文件的路径,
	第二个参数是struct stat的指针。

3、搭配stat函数使用的的常见宏

S_ISLNK(st_mode)	// 是否是一个连接.
S_ISREG(st_mode)	// 是否是一个常规文件.
S_ISDIR(st_mode)	// 是否是一个目录
S_ISCHR(st_mode)	// 是否是一个字符设备.
S_ISBLK(st_mode)	// 是否是一个块设备
S_ISFIFO(st_mode)	// 是否是一个FIFO文件.
S_ISSOCK(st_mode)	// 是否是一个SOCKET文件 

4、simple

#include <iostream>
#include <vector>
#include <string>
#include <dirent.h>
#include <cstdio>
#include <cstring>
#include <sys/stat.h>
using namespace std;
void FindFiles(string root ,vector<string> &files){
    DIR *dir;
    struct stat st;
    struct dirent *ent;
    if ((dir = opendir (root.c_str())) != NULL) {

        while ((ent = readdir (dir)) != NULL) {
            if(!strcmp(ent->d_name,".")||!strcmp(ent->d_name,".."))
                continue;
            files.push_back(ent->d_name);
            string name = root;
            name.append("/").append(ent->d_name);
            stat(name.c_str(),&st);
            if(S_ISDIR(st.st_mode))
            {
                FindFiles(name,files);
            }
            
        }
        closedir (dir);
    }
}


int main(){
    string filePath = "xxx/xxx/xxx";
    vector<string> files;

    FindFiles(filePath, files);

    int size = files.size();
    for(auto tmp : files) 
    {
        std::cout<<tmp<<std::endl;
    }

    return 0;
}
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值