opendir() chdir() 的问题
#include<stdio.h>#include<dirent.h>#include<unistd.h>#include<sys/stat.h>#include<string.h>void dppath(char *pathname,int num){ struct dirent *dirp; struct stat buf; DIR *dp; int i; if(chdir(pathname)==-1) //[color=#FF0000]1[/color] { printf("error or no exist pathname: %s\n",pathname); return; } if((dp=opendir(pathname))==NULL) //[color=#FF0000]2[/color] { printf("don't open :%s\n",pathname); return; } while((dirp=readdir(dp))!=NULL) { if(lstat(dirp->d_name,&buf)<0) { printf("lstat error\n"); return; } if(S_ISDIR(buf.st_mode)) { if(strcmp(dirp->d_name,".")==0 || strcmp(dirp->d_name,"..")==0) { continue; } for(i=0;i<num;i++) printf(" "); printf("%s\n",dirp->d_name); dppath(dirp->d_name,num+3); } else { for(i=0;i<num;i++) printf(" "); printf("%s\n",dirp->d_name); } } closedir(dp); chdir(".."); }int main(int argc,char *argv[]){ int num=3; if(argc!=2) { printf("usage: ftw <starting-pathname>\n"); return 0; } if(chdir(argv[1])==-1) { printf("error or no exist pathname: %s\n",argv[1]); return 0; } printf("%s\n",argv[1]); dppath(argv[1],num); return 0;}
7 void dppath(char *pathname,int num) 8 { 9 struct dirent *dirp; 10 struct stat buf; 11 char pbuf[32]; 12 DIR *dp; 13 int i; 14 getcwd(pbuf,32); 15 printf("current wd2:%s\n",pbuf); 16 if((dp=opendir(pathname))==NULL) //[color=#FF0000]2[/color] 17 { 18 printf("don't open :%s\n",pathname); 19 return; 20 if(chdir(pathname)==-1) //[color=#FF0000]1[/color] 21 { 22 printf("error or no exist pathname: %s\n",pathname); 23 return; 24 } 25 getcwd(pbuf,32); 26 printf("current wd2:%s\n",pbuf); 27 /* 28 if((dp=opendir(pathname))==NULL) //[color=#FF0000]2[/color] 29 { 30 printf("don't open :%s\n",pathname); 31 return; 32 } 33 */