【问题标题】:how to skip a directory while reading using dirent.h使用dirent.h阅读时如何跳过目录
【发布时间】:2012-04-30 23:55:36
【问题描述】:

我正在尝试使用 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()

【问题讨论】:

  • access 用两个 c 拼写。
  • 这段代码如何编译?您有一个名为dip 的变量,您将其称为dp。另外,将来,请缩进您的代码,以便于理解。
  • 您粘贴的代码太少,我们甚至无法理解问题出在哪里。 accessdirs 是否在循环中调用?当返回0 时,该循环会做什么?递归到底在哪里? “在这里做事”是否调用accessdirs
  • @Greg:你可能是对的,为什么要删除你的答案?该函数要么递归调用自身,要么在其调用者的循环内。最有可能的是,当它返回 0 时,会导致循环终止,而不继续处理同一目录中的其他条目。
  • 程序崩溃可能是因为您没有正确检查错误。我们需要看的代码在do things here

标签: c++ c opendir dirent.h


【解决方案1】:

你最大的问题似乎在这里:

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

没有看到fpath 的倾诉,很难确定,但你要么是

  • sprintf 调用中溢出 fpath,导致未定义的行为。 “系统卷信息”是一个长名称。你真的应该使用snprintf

  • 不检查stat 调用的返回值。如果返回-1,我不确定buf的内容是什么。

更重要的是,如果你可以使用 POSIX 的东西,函数 ftw 是标准的,应该提供你在这里尝试实现的大部分功能。

【讨论】:

  • 对不起。直到现在我才离开。我已经为 fpath 添加了声明行
猜你喜欢
  • 2014-03-14
  • 2015-08-27
  • 1970-01-01
  • 1970-01-01
  • 2011-12-13
  • 2012-09-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多