猿问

有个问题,chdir(dir);chdir("..")这两句为什么变更目录?

#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;

}

牛魔王的故事
浏览 328回答 3
3回答

犯罪嫌疑人X

最近也遇到了这个问题,但是有些想不通,chdir(dir)后续的程序,并没有更改某个量,readdir还是获取的dir的目录流,和进入该目录有什么关联吗

侃侃尔雅

因为为了让程序变得准确可行。  1、chdir("..");是为了在递归完某一子目录后,退回到其父目录继续遍历后续的普通文件或其他子目录;如果缺少这一语句,那么while循环中的递归printdir将会把父目录中后续的普通文件当作目录来操作,从而造成“无法打开目录”这种错误。  2、chdir(dir);是为了在程序刚运行时进入指定的目录,以及接下来递归时进入相应子目录;用`pwd`提取的绝对路径。  [gag@genomic-server tmp]$ more test1  #!/usr/bin/perl -w  # script name is test  use strict;  my $d="/home/gag";  my $now=`pwd`;  print $now,"\n";  chdir $d;  print `pwd`;print `ls`;  `touch iamhere`;  print "#######################\n";  chdir $now;print `pwd`;  `touch iamherethen`;  [gag@genomic-server tmp]$ perl test1  /home/gag/perl/tmp  /home/gag  c  cpp1  cpp2  java  perl  shell  tools  #######################  /home/gag  [gag@genomic-server tmp]$ ls  test1  [gag@genomic-server tmp]$ ls ../../  c cpp1 cpp2 iamhere iamherethen java perl shell tools

互换的青春

chdir(dir);是为了在程序刚运行时进入指定的目录,以及接下来递归时进入相应子目录;chdir("..");是为了在递归完某一子目录后,退回到其父目录继续遍历后续的普通文件或其他子目录;如果缺少这一语句,那么while循环中的递归printdir将会把父目录中后续的普通文件当作目录来操作,从而造成“无法打开目录”这种错误。【以上只是个人观点,但愿能帮到你^_^】
随时随地看视频慕课网APP
我要回答