S_ISDIR返回错误结果

来源:互联网 发布:php curl设置请求头 编辑:程序博客网 时间:2024/06/16 03:58
参考了2种遍历目录的写法
第一种:结果出错
int browse_dir(string dir)
{
        DIR *pDir;
        struct dirent *pEnt;
        struct stat statbuf;
        string sFileName;

        pDir = opendir(dir.c_str());
        if (pDir == NULL) {
                if (errno == ENOTDIR) {
                        filenames.push_back(dir);
                        return 0;
                }
                perror(dir.c_str());
                return -1;
        }
        while ((pEnt=readdir(pDir))!= NULL)
        {
                if ((pEnt->d_name[0]=='.')&&(pEnt->d_name[1]=='.' || pEnt->d_name[1]==0))
                {
                        continue;
                }

                //lstat(pEnt->d_name,&statbuf);

//将sprintf(fullpath, "%s/%s", dir.c_str(), pEnt->d_name); //获取全局路径

lstat(fullpath,&statbuf);

                if(!S_ISREG(statbuf.st_mode))//执行该代码后,无论是目录还是文件,均为true,所以只会打印出directory->。。。的结果,还有 如果把!S_ISREG改为S_ISDIR则把无论什么都会打印出file->.....
                {
                    sFileName= dir + "/" + pEnt->d_name;
                    printf("directory->%s\n", sFileName.c_str());
                //  browse_dir(sFileName);
                }
                else
                {
                    sFileName= dir +"/"+pEnt->d_name;
                    printf("file->%s\n",sFileName.c_str());
                }
        }
        closedir(pDir);
        return 0;
}
第2种写法:结果正确
void printdir(char *dir,int depth)
{
DIR *dp;
struct dirent *entry;
struct stat statbuf;

if((dp=opendir(dir))==NULL)
{
fprintf(stderr,"cannot open direntory:%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);
}
0 0
原创粉丝点击