当前位置:   article > 正文

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

c++ 遍历文件夹

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

头文件"fileNames.h"

  1. #ifndef __FILENAMES__
  2. #define __FILENAMES__
  3. #include <stdio.h>
  4. #include <vector>
  5. #include <string>
  6. #include <sys/types.h>
  7. #include <dirent.h>
  8. #include <algorithm>
  9. #include <iostream>
  10. #include <cstring>
  11. void getFiles(const std::string& path,const std::string& file_extension, std::vector<std::string>& filepaths,std::vector<std::string>& filenames);
  12. bool cmpName(std::string& s1,std::string& s2);
  13. #endif

path:文件夹路径

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

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

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

CPP文件"fileNames.cpp"

  1. #include "fileNames.h"
  2. void getFiles(const std::string& path,const std::string& file_extension, std::vector<std::string>& filepaths,std::vector<std::string>& filenames)
  3. {
  4. DIR *pDir;
  5. struct dirent* ptr;
  6. if(!(pDir = opendir(path.c_str()))){
  7. std::cout<<"Folder doesn't Exist!"<<std::endl;
  8. return;
  9. }
  10. while((ptr = readdir(pDir))!=0) {
  11. if (strcmp(ptr->d_name, ".") != 0 && strcmp(ptr->d_name, "..") != 0){
  12. //filepaths.push_back(path + "/" + ptr->d_name);
  13. // convert name to string
  14. std::string name(ptr->d_name);
  15. // find the file name extension segment index
  16. int pos=name.find_last_of('.');
  17. // get the extension
  18. std::string extension = name.substr(pos+1,-1);
  19. if(!strcmp(file_extension.c_str(),extension.c_str()) ){
  20. filenames.push_back(ptr->d_name);
  21. filepaths.push_back(path + "/" + ptr->d_name);
  22. }
  23. }
  24. }
  25. closedir(pDir);
  26. }
  27. bool cmpName(std::string& s1,std::string& s2){
  28. int sub_len = 16;
  29. std::string s1_sub = s1.substr(0,sub_len);
  30. std::string s2_sub = s2.substr(0,sub_len);
  31. double s1_num = std::atol(s1_sub.c_str());
  32. double s2_num = std::atol(s2_sub.c_str());
  33. return s1_num < s2_num ? 1:0;
  34. }

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

声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号