[英]how to skip a directory while reading using dirent.h
i am trying to recursively open files using the functionality provided in dirent.h 我正在尝试使用dirent.h中提供的功能递归打开文件
My problem is: i could not make it to skip directories which failed to open. 我的问题是:我无法跳过无法打开的目录。 I want it to open the directories which it can and skip those which it can't and move to the next directory instead of exiting with failure.
我希望它打开它可以打开的目录,并跳过它不能打开的目录,然后移到下一个目录,而不是失败退出。 What should i do to fix this?
我应该怎么做才能解决这个问题?
Here is a simple code i tried to use 这是我尝试使用的简单代码
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;
}
I used this same style on windows 7
and it works fine.But it crashed on windows xp
and when i debugged it i found that it crashes while trying to open "system volume information"
. 我在
windows 7
上使用了相同的样式,但效果很好。但是在windows xp
上崩溃了,当我对其进行调试时,我发现它在尝试打开"system volume information"
时崩溃了。 I really dont need to access this folder and i was hoping if there is any way to skip it. 我真的不需要访问此文件夹,我一直希望是否可以跳过它。
Here is my real code: 这是我的真实代码:
It is a little bit long. 它有点长。
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()
Your biggest problem seems to be here: 您最大的问题似乎在这里:
sprintf(fpath,"%s\\%s",path,entry->d_name);
stat(fpath, &buf);
Without seeing fpath
's declatation, it's tough to tell for certain, but you're either 没有看到
fpath
的描述,很难确定,但您要么
Overflowing fpath
in the sprintf
call, leading to undefined behavior. sprintf
调用中的fpath
溢出,导致未定义的行为。 "System Volume Information" is a long name. “系统卷信息”是一个长名称。 You should really use
snprintf
. 您应该真正使用
snprintf
。
Not checking the return value of the stat
call. 不检查
stat
调用的返回值。 If it returns -1
, I'n not sure what the contents of buf
will be. 如果返回
-1
,我不确定buf
的内容是什么。
More importantly, if you can use POSIX stuff, the function ftw
is standard, and should provide most of the functionality you're trying to implement here. 更重要的是,如果您可以使用POSIX东西,则函数
ftw
是标准的,应该提供您尝试在此处实现的大多数功能。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.