C++ 遍历文件夹及其子文件(夹)

C++ 遍历文件夹及其子文件(夹)


代码如下

int _Finder(LPCTSTR pstr)
{
 CFileFind finder ;
 CString strWildcard(pstr) ;
 strWildcard += _T("//*.*") ;

 BOOL bWorking = finder.FindFile( strWildcard ) ;
 
 int i = 0 ;
 while(bWorking)
 {
  //bWorking = finder.FindNextFile() & finder.isDots() & finder.IsDirectory();
  //Nonzero if the found file has the name "." or "..", which indicates that the found file is actually a directory. Otherwise 0
  /*
  bWorking = finder.FindNextFile() ;
  if (!bWorking)
  break ;
  */
  //如果还有文件存在就执行下面的
  bWorking = finder.FindNextFile() ;
  if ( finder.IsDots() ) //如果是. 或者.. 就continue
  {
   bWorking = finder.FindNextFile() ;
   continue ;
  }
   //一般文件及文件夹
 
  printf("%d   %s/n " , ++i ,  finder.GetFileName()) ;
  BOOL bisDir = finder.IsDirectory() ;
  if( bisDir )
  { //是文件夹
   CString repath = finder.GetFilePath() ;
   _Finder( repath ) ;
  }
  else
  {//是文件
   
   //do parse
   CString repath = finder.GetFilePath() ; //eg return c:/myhtml/myfile.txt

 
 
  }
 
 
 }//end while
 finder.Close() ;
 return 1 ;
}

 

有以下以点可能大家不明白之处,

IsDots是作什么用的?

IsDots是判断当前的文件是否是.或者..文件,windows下的每个文件夹下都有这两个文件的,..表示上级目录,.表示当前目录,桌面windows是看不到的, 下面的方法可以看到.和.. ,进入命令行,输入dir ,就会显示当前文件夹下的所有目录,同时你也会发现.及.. ,程序运行时必须去除这两个,防止endless loop

 

 

你可能会碰到少读一个文件,我一开始就犯了这样的错误,还以为是MS的一个bug里,原来是我的bug~

你的findnextifle肯定没有按号入坐

可能是while( finder.filenextfile() )这样写的,你就漏了第一个文件,不信试试看~

还有大家写遍历时发现少了最后一个文件,

我猜你可能是这样写的

bworking = finder.findnextfile() ;

while(bworking)

{

     bworking = finder.findnextfile() ;

     //do something

     ......

}

这样就少了最后一个文件!

少了文件那是logic问题~好搞定~

遍历文件里有固定顺序的,看参照正文

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值