| 
 
| 第三章第八节有一个扫描目录的程序,怎么进入各个目录进行遍历我知道了,但是返回上级目录继续遍历那个我就不太理解了,书上说他是靠chdir("..")进入上一级的,但是这个函数在while之外,那他执行了这个之后不就直接退出了printdir这个函数了吗 上代码 #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;
 | 
 |