打印

linux程序设计这本书上的一个例子

[复制链接]
2301|1
手机看帖
扫描二维码
随时随地手机跟帖
跳转到指定楼层
楼主
啥是arm|  楼主 | 2013-4-5 19:23 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式
第三章第八节有一个扫描目录的程序,怎么进入各个目录进行遍历我知道了,但是返回上级目录继续遍历那个我就不太理解了,书上说他是靠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;

相关帖子

沙发
阿南| | 2013-4-5 22:37 | 只看该作者
恩,看来只能是仔细看书,加运行代码测试了。

使用特权

评论回复
发新帖 我要提问
您需要登录后才可以回帖 登录 | 注册

本版积分规则

46

主题

181

帖子

0

粉丝