S_ISDIR返回錯誤結果

參考了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);
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章