日期:2014-05-16  浏览次数:20802 次

opendir() chdir() 的问题
C/C++ code


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






为什么 注解1 和注解 2 标记 的两个if语句换一下位置后运行时,会出现opendir 无法打开目录文件呢 ??

------解决方案--------------------
经过测试是你没有判断目录和文件,所以导致以打开目录的方式来打开文件,会出错,我添加了的代码如下
C/C++ code
  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 */