c++ 遍历文件夹下所有文件

常见的文件遍历方式是基于boost 库的filesystem做文件遍历,但是boost库配置cmakelists.txt时不是很方便,所以在网上找到一种比较简单的方法,由于当时没有记录下原始作者链接,未能建立引用,想作者隔空表示抱歉

头文件"fileNames.h"

#ifndef __FILENAMES__
#define __FILENAMES__

#include <stdio.h>
#include <vector>
#include <string>
#include <sys/types.h>
#include <dirent.h>
#include <algorithm>
#include <iostream>
#include <cstring>

void getFiles(const std::string& path,const std::string& file_extension,  std::vector<std::string>& filepaths,std::vector<std::string>& filenames);
bool cmpName(std::string& s1,std::string& s2);

#endif

path:文件夹路径

file_extension:需要遍历的文件类型扩展名,如json

filepaths:找到特定类型文件的完整路径

filenames:找到的特定类型文件的文件名

CPP文件"fileNames.cpp"

#include "fileNames.h"


void getFiles(const std::string& path,const std::string& file_extension,  std::vector<std::string>& filepaths,std::vector<std::string>& filenames)
{
	DIR *pDir;
    struct dirent* ptr;
    if(!(pDir = opendir(path.c_str()))){
        std::cout<<"Folder doesn't Exist!"<<std::endl;
        return;
    }
    while((ptr = readdir(pDir))!=0) {
        if (strcmp(ptr->d_name, ".") != 0 && strcmp(ptr->d_name, "..") != 0){
            //filepaths.push_back(path + "/" + ptr->d_name);
            // convert name to string
            std::string name(ptr->d_name);
            // find the file name extension segment index
            int pos=name.find_last_of('.');
            // get the extension
            std::string extension = name.substr(pos+1,-1);
            if(!strcmp(file_extension.c_str(),extension.c_str()) ){
                filenames.push_back(ptr->d_name);
                filepaths.push_back(path + "/" + ptr->d_name);
            }
    	}
    }
    closedir(pDir);
}

bool cmpName(std::string& s1,std::string& s2){
    int sub_len = 16;
    std::string s1_sub = s1.substr(0,sub_len);
    std::string s2_sub = s2.substr(0,sub_len);
    double s1_num = std::atol(s1_sub.c_str());
    double s2_num = std::atol(s2_sub.c_str());
    return s1_num < s2_num ? 1:0;
}

cmpName函数是用于文件名称排序的,可以根据自己的需要去自己实现。因为这种方法找出的文件名称顺序并没有按照文件名排序,但是我们通常在处理数据文件的时候,文件是按照日期或者数字排序的,所以要实现排序功能可以自行添加。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值