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