较常见的遍历算法基于stat实现,例如:
if( stat( path, &_stbuf ) == 0 )
if( S_ISDIR( _stbuf.st_mode ))
{
//is a folder
_dir = opendir( path );
if( _dir )
{
travel_dir(...);
}
}
else
{
//is a file
}
但基于stat的算法,受限于stat的性能,在一些极端情况下(如,一个目录下有数千个文件时,stat的性能会逐渐变差,类似O(n2)的算法性能),因此在对遍历的时间性能要求较高的情况下,此算法不合适。
考虑到遍历时,如果对文件其他的属性并不关注,可以不使用stat系统调用,只判断是否是目录即可,因此算法可以调整为:
_dir = opendir( path );
if( _dir )
{
while(( _file = readdir( _dir )) != NULL )
{
if( _file->d_type == DT_DIR )
{
//is a folder
travel_dir(...);
}
else
{
//is a file
}
}
}
此算法简单遍历所有目录,性能为O(n),与文件系统的文件数为线性关系。与上面的算法比,平均有几十倍的性能提升。