windows和linux获取文件夹内容的一种方法

windows:

使用头文件:<io.h>、<direct.h>

关键函数:_findfirst、_findnext

关键结构体:_finddata_t

[cpp]  view plain  copy
  1. _finddata_t fileinfo;  
  2. intptr_t hFile;  
  3. string root;  
  4. root.assign(Path);//文件夹绝对路径  
  5. int len = root.length();  
  6.   
  7. if ( !IsEndObliqueLine(Path) )//路径的结尾不是‘\’  
  8. {  
  9.     root.append("\\");  
  10. }  
  11. root.append("*");//路径下的所有文件  
  12.   
  13. hFile = _findfirst(root.c_str(), &fileinfo);  
  14. if ( -1 == hFile)  
  15. {  
  16.     assert(false);  
  17.     return;  
  18. }  
  19. strcpy(m_CurrentPath, Path);//保存到m_CurrentPath  
  20. //清空之前Path的信息  
  21. FilesPathVector.clear();//自定义的保存信息的容器  
  22. do //保存信息  
  23. {  
  24.     LISTCMD_INFO TmpDirInfo = {0};  
  25.     TransFileInfo(fileinfo, TmpDirInfo);  
  26.     FilesPathVector.push_back(TmpDirInfo);  
  27. }while(_findnext(hFile, &fileinfo)   ==   0);  

linux:

使用头文件: <dirent.h>、 <sys/types.h>、<sys/stat.h>

关键函数:readdir、lstat

关键结构体:dirent

[cpp]  view plain  copy
  1. <span style="white-space:pre;"> </span>DIR *dir;  
  2.     if ( !(dir = opendir(Path)) )  
  3.     {  
  4.         assert(false);  
  5.         return;  
  6.     }  
  7.     <span style="white-space:pre;"> </span>strcpy(m_CurrentPath, Path);//保存到m_CurrentPath  
  8.     struct dirent *d_ent;  
  9.     char fullpath[128];  
  10.     FilesPathVector.clear();  
  11.     while ( (d_ent = readdir(dir)) != NULL )  
  12.     {  
  13.         struct stat file_stat;  
  14.         //if ( strncmp(d_ent->d_name, ".", 1) == 0 )  
  15.         //{  
  16.         //  continue;   // 忽略"."目录  
  17.         //}  
  18.         memset(fullpath, '\0'sizeof(fullpath));  
  19.         strcpy( fullpath,  Path);  
  20.         if ( !strcmp(fullpath, "/") )  
  21.         {  
  22.             fullpath[0] = '\0';  
  23.         }  
  24.         strcat(fullpath, "/");  
  25.         strcat(fullpath, d_ent->d_name);  
  26.         if ( lstat(fullpath, &file_stat) < 0 )  
  27.         {  
  28.             assert(false);  
  29.             return;  
  30.         }  
  31.         //保存信息到自己的数据结构,在函数外面保存文件名  
  32.         LISTCMD_INFO TmpDirInfo = {0};  
  33.         strcpy(TmpDirInfo.cFileName, d_ent->d_name);  
  34.         TransFileInfo(&file_stat, TmpDirInfo);  
  35.         FilesPathVector.push_back(TmpDirInfo);  
  36.     }  
  37.     closedir(dir);  


值得注意的是,此种方法windows的路径分隔是用'\',而linux用'/',使用时多少有点不便。

如果有其他更好得方法,欢迎交流!

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值