您的位置:首页 > 编程语言 > C语言/C++

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

2009-04-16 19:48 232 查看
代码如下

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了
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: