【发布时间】: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