首页 > 编程 > C++ > 正文

C++遍历文件夹下文件的方法

2020-05-23 14:18:12
字体:大 中 小
来源:转载
供稿:网友

这篇文章主要介绍了C++遍历文件夹下文件的方法,实例分析了C++针对文件夹遍历的相关技巧,具有一定参考借鉴价值,需要的朋友可以参考下

本文实例讲述了C++遍历文件夹下文件的方法。分享给大家供大家参考。具体如下:

 

 
  1. #include <windows.h> 
  2. #include <stdio.h> 
  3. #include <string.h> 
  4. #define LEN 1024 
  5. // 深度优先递归遍历目录中所有的文件 
  6. BOOL DirectoryList(LPCSTR Path) 
  7. { 
  8. WIN32_FIND_DATA FindData; 
  9. HANDLE hError; 
  10. int FileCount = 0; 
  11. char FilePathName[LEN]; 
  12. // 构造路径 
  13. char FullPathName[LEN]; 
  14. strcpy(FilePathName, Path); 
  15. strcat(FilePathName, "//*.*"); 
  16. hError = FindFirstFile(FilePathName, &FindData); 
  17. if (hError == INVALID_HANDLE_VALUE) 
  18. { 
  19. printf("搜索失败!"); 
  20. return 0; 
  21. } 
  22. while(::FindNextFile(hError, &FindData)) 
  23. { 
  24. // 过虑.和.. 
  25. if (strcmp(FindData.cFileName, ".") == 0  
  26. || strcmp(FindData.cFileName, "..") == 0 ) 
  27. { 
  28. continue; 
  29. } 
  30. // 构造完整路径 
  31. wsprintf(FullPathName, "%s//%s", Path,FindData.cFileName); 
  32. FileCount++; 
  33. // 输出本级的文件 
  34. printf("/n%d %s ", FileCount, FullPathName); 
  35.  
  36. if (FindData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) 
  37. { 
  38. printf("<Dir>"); 
  39. DirectoryList(FullPathName); 
  40. } 
  41. } 
  42. return 0; 
  43. } 
  44. void main() 
  45. { 
  46. DirectoryList("D:eclipse-J2EE"); 
  47. } 

希望本文所述对大家的C++程序设计有所帮助。

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表