当前位置:   article > 正文

C++:遍历指定路径下的文件/图片_c++ 遍历文件夹下的图片

c++ 遍历文件夹下的图片
  1. #include <iostream>
  2. #include <vector>
  3. #include <io.h>
  4. using namespace std;
  5. bool get_filelist_from_dir(std::string path, std::vector<std::string>& files)
  6. {
  7. long long hFile = 0;
  8. //_findnext()第一个参数”路径句柄”,返回的类型为intptr_t(long long),
  9. //如果定义为long,在win7中是没有问题,但是在win10中就要改为long long或者intptr_t
  10. struct _finddata_t fileinfo;
  11. files.clear();
  12. if ((hFile = _findfirst(path.c_str(), &fileinfo)) != -1)
  13. {
  14. do
  15. {
  16. cout << fileinfo.name << endl;
  17. if (!(fileinfo.attrib & _A_SUBDIR))
  18. {
  19. files.push_back(fileinfo.name);
  20. }
  21. } while (_findnext(hFile, &fileinfo) == 0);
  22. _findclose(hFile);
  23. return true;
  24. }
  25. else
  26. {
  27. return false;
  28. }
  29. //另一种写法
  30. //struct _finddata_t fileinfo;
  31. //long long handle;
  32. _findnext()第一个参数”路径句柄”,返回的类型为intptr_tlong long),
  33. 如果定义为long,在win7中是没有问题,但是在win10中就要改为long long或者intptr_t
  34. //handle = _findfirst(path.c_str(), &fileinfo); //返回文件句柄<br>
  35. //if (handle == -1)
  36. //{
  37. // cout << "fail..." << endl;
  38. // return false;
  39. //}
  40. //else
  41. //{
  42. // cout << fileinfo.name << endl;
  43. // files.push_back(fileinfo.name);
  44. //}
  45. //cout << "#### 1 ####" << endl;
  46. //while (!_findnext(handle, &fileinfo))
  47. //{
  48. // cout << "#### 2 ####" << endl;
  49. // cout << fileinfo.name << endl;
  50. //}
  51. //_findclose(handle);
  52. //return true;
  53. }
  54. vector<string> getImageList(std::string file_path, std::string suffix)
  55. {
  56. //string file_path = "D:\\image\\";
  57. //string suffix = "*.png";
  58. string search_path = file_path + suffix;
  59. vector<string> file_list;//保存遍历到的文件name
  60. if (!get_filelist_from_dir(search_path, file_list))
  61. cout << "open file error!" << endl;
  62. vector<string> image_path_list;//保存文件绝对路径
  63. for (int i = 0; i < file_list.size(); i++)
  64. {
  65. image_path_list.push_back(file_path + file_list[i]);
  66. //Mat image = imread(image_path);
  67. //这里可以对图像进行处理
  68. }
  69. return image_path_list;
  70. }
  71. int main()
  72. {
  73. vector<string> output;
  74. string filepath = "D:\\image\\";
  75. string suffix = "*.*";//后缀名
  76. output = getImageList(filepath, suffix);
  77. return 0;
  78. }

涉及到了一个结构体,需要用的是name属性,当然假如需要文件大小的话也可以把size提取出来

  1. #define _finddata_t _finddata64i32_t
  2. struct _finddata64i32_t
  3. {
  4. unsigned attrib;
  5. __time64_t time_create; // -1 for FAT file systems
  6. __time64_t time_access; // -1 for FAT file systems
  7. __time64_t time_write;
  8. _fsize_t size;
  9. char name[260];
  10. };

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小小林熬夜学编程/article/detail/281798
推荐阅读
相关标签
  

闽ICP备14008679号