C++ 批量读取文件夹中的文件名

使用C++批量读取文件名 

1 Linux 单级目录

#include <sys/types.h>
#include <dirent.h>
#include <unistd.h>
#include <string>
#include <vector>

using namespace std;

DIR* dir;
struct dirent* ptr;
vector<string> fileList; 
dir = opendir("/home/lumeiqi/projects/DecodeTest/testvideo");
while((ptr = readdir(dir)) != NULL)
{
    if(strcmp(ptr->d_name,".") != 0 && strcmp(ptr->d_name,"..") != 0)
    {
        cout<<"filename"<<ptr->d_name<<endl;
        fileList.push_back(ptr->d_name);    

    } 
}
closedir(dir);

2 Linux 多级目录嵌套

读一个路径下所有的文件,不管有多少文件夹,递归一下就可以了

#include <dirent.h>
#include <iomanip>
#include <string.h>
#include <string>

void ReadFile(const std::string filePath)
{
    DIR* dir = opendir(filePath.c_str());
    struct dirent* ptr; 
    while ((ptr = readdir(dir)) != NULL) {
        //if(ptr->d_name != "." && ptr->d_name != "..")
        if (strcmp(ptr->d_name,".") != 0 && strcmp(ptr->d_name,"..") != 0) {
             std::string subDirect = filePath;
            //d_type 文件(8)、目录(4)
            if (ptr->d_type == 4) {
               // cout<<ptr->d_name<<endl;
                subDirect += "/";
                subDirect += ptr->d_name;
                ReadFile(subDirect);

            } else if(ptr->d_type == 8) {
               // cout<<ptr->d_name<<endl;
                std::string absolutePath = subDirect + "/";
                absolutePath += ptr->d_name; 
            }
        }
    }
}

3 Windows 多级目录嵌套

使用

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值