亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

有個問題,chdir(dir);chdir("..")這兩句為什么變更目錄?

有個問題,chdir(dir);chdir("..")這兩句為什么變更目錄?

牛魔王的故事 2022-08-04 17:13:01
#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;}
查看完整描述

3 回答

?
犯罪嫌疑人X

TA貢獻2080條經驗 獲得超4個贊

最近也遇到了這個問題,但是有些想不通,chdir(dir)后續的程序,并沒有更改某個量,readdir還是獲取的dir的目錄流,和進入該目錄有什么關聯嗎

查看完整回答
反對 回復 2022-08-08
?
侃侃爾雅

TA貢獻1801條經驗 獲得超16個贊

因為為了讓程序變得準確可行。
  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


查看完整回答
反對 回復 2022-08-08
?
互換的青春

TA貢獻1797條經驗 獲得超6個贊

  1. chdir(dir);是為了在程序剛運行時進入指定的目錄,以及接下來遞歸時進入相應子目錄;

  2. chdir("..");是為了在遞歸完某一子目錄后,退回到其父目錄繼續遍歷后續的普通文件或其他子目錄;如果缺少這一語句,那么while循環中的遞歸printdir將會把父目錄中后續的普通文件當作目錄來操作,從而造成“無法打開目錄”這種錯誤。

【以上只是個人觀點,但愿能幫到你^_^】


查看完整回答
反對 回復 2022-08-08
  • 3 回答
  • 0 關注
  • 359 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號