求助,以下是《linux程序设计》 的一段代码,单步调试时发现一个很奇怪的现象,程序运行到 36 行 : closedir(dp); 再单步运行,程序会跑到 18 行: while((entry=readdir(dp))!=NULL),好像不是很符合c语言的逻辑?
1#include<dirent.h>
2 #include<sys/types.h>
3 #include<string.h>
4 #include<stdio.h>
5 #include<stdlib.h>
6 #include <sys/stat.h>
7 #include <unistd.h>
8 void printfdir(char * dir, int depth)
9 { DIR *dp;
10 struct dirent *entry;
11 struct stat statbuf;
12 if((dp=opendir(dir) )==NULL)
13 {
14 fprintf(stderr,"can't open dir%s\n",dir);
15 return;
16 }
17 chdir(dir );
18 while((entry=readdir(dp))!=NULL)
19 {
20 lstat(entry->d_name,&statbuf);
21 if(S_ISDIR(statbuf.st_mode))
22 {
23 if((strcmp(".",entry->d_name)==0)||( strcmp("..",entry->d_name)==0))
24
25
26 continue;
27 printf("%*s%s/\n",depth,"",entry->d_ name);
28
29 printfdir(entry->d_name,depth+4);
30 }
31 else
32
33 printf("%*s%s/\n",depth,"",entry->d_ name);
34 }
35 chdir("..");
36 closedir(dp);
37
}
40 int main()
41 {
42 printf("scan /share/begin_linux:\n");
43 printfdir("/share/begin_linux/",0);
44 exit(0);
45 }
1#include<dirent.h>
2 #include<sys/types.h>
3 #include<string.h>
4 #include<stdio.h>
5 #include<stdlib.h>
6 #include <sys/stat.h>
7 #include <unistd.h>
8 void printfdir(char * dir, int depth)
9 { DIR *dp;
10 struct dirent *entry;
11 struct stat statbuf;
12 if((dp=opendir(dir) )==NULL)
13 {
14 fprintf(stderr,"can't open dir%s\n",dir);
15 return;
16 }
17 chdir(dir );
18 while((entry=readdir(dp))!=NULL)
19 {
20 lstat(entry->d_name,&statbuf);
21 if(S_ISDIR(statbuf.st_mode))
22 {
23 if((strcmp(".",entry->d_name)==0)||( strcmp("..",entry->d_name)==0))
24
25
26 continue;
27 printf("%*s%s/\n",depth,"",entry->d_ name);
28
29 printfdir(entry->d_name,depth+4);
30 }
31 else
32
33 printf("%*s%s/\n",depth,"",entry->d_ name);
34 }
35 chdir("..");
36 closedir(dp);
37
}
40 int main()
41 {
42 printf("scan /share/begin_linux:\n");
43 printfdir("/share/begin_linux/",0);
44 exit(0);
45 }