引数で指定したディレクトリが持つ全ての子ディレクトリのみ全て表示するプログラムを作っています。
再帰させる
dirwalk(dp->d_name,level+1)を消すと1つ下の階層のディレクトリだけ全て表示させられますが、この一文を加えるとstatのperrorが表示されて思うように出力されません。
理想とする出力結果
$./a.out Dir
DirA
_Dir1
__Dira
__Dirb
_Dir2
DirB
DirC
(_は空白文字で置き換えてください)
よろしくお願いします
C
1#include <stdio.h> 2#include <string.h> 3#include <dirent.h> 4#include <unistd.h> 5#include <sys/types.h> 6#include <sys/stat.h> 7 8void dirwalk(char* dname,int level){ 9 chdir(dname); 10 char buf[512]; 11 if(getcwd(buf,sizeof(buf))==NULL){return;} 12 DIR* dfd = opendir("."); 13 if(dfd == NULL){return;} 14 struct dirent* dp; 15 for(dp=readdir(dfd);dp!=NULL;dp=readdir(dfd)){ 16 if(strcmp(dp->d_name,".") == 0 ||strcmp(dp->d_name,"..") == 0){ 17 continue; 18 } 19 struct stat s; 20 if(stat(dp->d_name,&s)==-1){perror("stat");} 21 if((s.st_mode&S_IFMT)==S_IFDIR){ 22 for(int i=0;i<level;i++){putchar(' ');} 23 printf("%s\n",dp->d_name); 24 } 25 dirwalk(dp->d_name,level+1); 26 } 27 chdir(".."); 28} 29 30int main(int argc, char* argv[]) { 31 if(argc!=2){ 32 printf("usage: %s dirname\n",argv[0]); 33 } 34 dirwalk(argv[1],0); 35 36 return 0; 37}
まずは、statがエラーの際のerrnoをご確認されてはいかがでしょうか?