簡體   English   中英

如何在使用dirent.h時跳過目錄

[英]how to skip a directory while reading using dirent.h

我正在嘗試使用dirent.h中提供的功能遞歸打開文件

我的問題是:我無法跳過無法打開的目錄。 我希望它打開它可以打開的目錄,並跳過它不能打開的目錄,然后移到下一個目錄,而不是失敗退出。 我應該怎么做才能解決這個問題?

這是我嘗試使用的簡單代碼

int acessdirs(const char *path)
{
    struct dirent *entry;
    DIR *dp;
    char fpath[300];
    if(dp=opendir(path))
    {
        while((entry=readdir(dp)))
            do things here
    }
    else
    {
        std::cout<<"error opening directory";
        return 0;
    }
    return 1;
}

我在windows 7上使用了相同的樣式,但效果很好。但是在windows xp上崩潰了,當我對其進行調試時,我發現它在嘗試打開"system volume information"時崩潰了。 我真的不需要訪問此文件夾,我一直希望是否可以跳過它。

這是我的真實代碼:

它有點長。

int listdir(const char *path) 
{
  struct dirent *entry;
  DIR *dp;

  if(dp = opendir(path))
  {
    struct stat buf ;

    while((entry = readdir(dp)))
    {
        std::string p(path);
        p += "\\";
        p += entry->d_name;
         char fpath[300];
        if(!stat(p.c_str(), &buf))
        {
            if(S_ISREG(buf.st_mode))
            {  
                sprintf(fpath,"%s\\%s",path,entry->d_name);
                stat(fpath, &buf);
                std::cout<<"\n Size of \t"<<fpath<<"\t"<<buf.st_size;
                fmd5=MDFile (fpath);        
            }//inner second if
            if(S_ISDIR(buf.st_mode) &&  
         // the following is to ensure we do not dive into directories "." and ".."
                      strcmp(entry->d_name, ".")  && strcmp(entry->d_name, "..") )
            {
                listdir(p.c_str());
            }
        }//inner first if
        else
            std::cout << "ERROR in stat\n";
    }//end while
    closedir(dp);
  }//first if
  else
  {
      std::cout << "ERROR in opendir\n";
      return 0;
  }
  return 1;   

 }//listdir()

您最大的問題似乎在這里:

sprintf(fpath,"%s\\%s",path,entry->d_name);
stat(fpath, &buf);

沒有看到fpath的描述,很難確定,但您要么

  • sprintf調用中的fpath溢出,導致未定義的行為。 “系統卷信息”是一個長名稱。 您應該真正使用snprintf

  • 不檢查stat調用的返回值。 如果返回-1 ,我不確定buf的內容是什么。

更重要的是,如果您可以使用POSIX東西,則函數ftw是標准的,應該提供您嘗試在此處實現的大多數功能。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM