当前位置:   article > 正文

C++ 遍历文件夹_c++遍历文件夹

c++遍历文件夹

遍历当前目录下的文件,不含多级目录

  1. /****************************************
  2. * 遍历当前目录下的文件夹和文件,默认是按字母顺序遍历
  3. ****************************************/
  4. #include<io.h>
  5. #include<iostream>
  6. using namespace std;
  7. bool FindAllFilesOnCurFolder(string path, int &file_num)
  8. {
  9. _finddata_t file_info;
  10. //可以定义后面的后缀为*.exe,*.txt等来查找特定后缀的文件,*.*是通配符,匹配所有类型,路径连接符最好是左斜杠/,可跨平台
  11. string current_path = path + "/*.*";
  12. int handle = _findfirst(current_path.c_str(), &file_info);
  13. //返回值为-1则查找失败
  14. if (-1 == handle)
  15. return false;
  16. do
  17. {
  18. string attribute;
  19. if (file_info.attrib == _A_SUBDIR) //是目录
  20. attribute = "dir";
  21. else
  22. attribute = "file";
  23. //获得的最后修改时间是time_t格式的长整型
  24. cout << file_info.name << ' ' << file_info.time_write << ' ' << file_info.size << ' ' << attribute << endl;
  25. file_num++;
  26. } while (!_findnext(handle, &file_info));
  27. //关闭文件句柄
  28. _findclose(handle);
  29. return true;
  30. }

多级目录遍历文件

  1. /*
  2. *深度优先递归遍历当前目录下的文件夹、文件及子文件夹和文件
  3. */
  4. #include<io.h>
  5. #include<iostream>
  6. using namespace std;
  7. void DfsListFolderFiles(string path)
  8. {
  9. _finddata_t file_info;
  10. string current_path = path + "/*.*";
  11. int handle = _findfirst(current_path.c_str(), &file_info);
  12. //返回值为-1则查找失败
  13. if (-1 == handle)
  14. {
  15. cout << "cannot match the path" << endl;
  16. return;
  17. }
  18. do
  19. {
  20. //目录
  21. if (file_info.attrib == _A_SUBDIR)
  22. {
  23. cout << file_info.name << endl;
  24. //.是当前目录,..是上层目录,须排除掉这两种情况
  25. if (strcmp(file_info.name, "..") != 0 && strcmp(file_info.name, ".") != 0)
  26. DfsListFolderFiles(path);
  27. }
  28. else
  29. {
  30. cout << file_info.name << endl;
  31. }
  32. } while (!_findnext(handle, &file_info));
  33. //关闭文件句柄
  34. _findclose(handle);
  35. }

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

闽ICP备14008679号