一个linux下的C语言目录扫描程序,看不懂,求注释!越详细越好啊。会追加悬赏的!!

#include <sys/types.h>
#include <sys/stat.h>
#include <dirent.h>
#include <stdio.h>
void printdir(char *dir,int depth)
{
DIR *dp;
struct dirent *entry;
struct stat statbuf;
if((dp=opendir(dir))==NULL)
{
fprintf(stderr,"cannot open directory:%s\n",dir);
return;
}
chdir(dir);
while((entry=readdir(dp))!=NULL)
{
lstat(entry->d_name,&statbuf);
if(S_ISDIR(statbuf.st_mode))
{
if(strcmp(".",entry->d_name)==0||strcmp("..",entry->d_name)==0)
continue;
printf("%*s%s/\n",depth,"",entry->d_name);
printdir(entry->d_name,depth+4);

}
else printf("%*s%s\n",depth,"",entry->d_name);
}
chdir("..");
closedir(dp);
}
int main()
{
printf("Directory scan of /home:\n");
printdir("/home",0);
printf("done.\n");
return 0;

}

其实递归这种东西你如果理解了,根本不需要注释,如果不理解再多的注释还是不懂,这个是linux程序设计中的一段经典代码,代码的核心其实就这几句
if(S_ISDIR(statbuf.st_mode))
{
if(strcmp(".",entry->d_name)==0||strcmp("..",entry->d_name)==0)
continue;
printf("%*s%s/\n",depth,"",entry->d_name);
printdir(entry->d_name,depth+4);
}
首先确定是目录,要不然直接输出,然后如果的当前目录(.)或者父目录(..),则执行下一个循环其实就是跳过这两个目录,printf("%*s%s/\n",depth,"",entry->d_name);这句其实就是让显示的好看点,根据depth决定要打印出几个空格,书上有关于&*s的用法,接着就是再一次递归。。。。这个解释不来,只能意会不能言传。
温馨提示:答案为网友推荐,仅供参考
第1个回答  2012-10-28
就是个遇到目录递归调用,文件就打印,‘.'是当前,'..'是上层
第2个回答  2012-10-30
学习
相似回答