【发布时间】:2012-03-16 13:55:34
【问题描述】:
我正在编写一个程序来模仿find 的一些行为,它遍历目录树并在找到的文件上调用lstat 以确定它们的类型。真正的find 将忽略用户在该目录中没有 R 或 X 访问权限的文件。我似乎无法复制这种行为;即使执行此操作的代码位于检查access() 的块内,我的代码也会继续调用lstat 并获得非法搜索错误(这是我试图阻止的)。
我的第一个想法是,也许第二个 access() 调用应该在路径上而不是路径/文件名上,但这似乎也不起作用(而且它不是多余的吗?)
任何指导将不胜感激。
我的代码(为简洁起见,我删除了错误捕获和其他内容):
void open_dir( char *dir, char *pattern, char type )
{
DIR *d;
struct dirent *de;
if ( access(dir, (R_OK | X_OK)) == 0 )
{
d = opendir(dir);
while( ( de = readdir(d) ) )
examine_de( de, dir, pattern, type );
closedir(d);
}
}
void examine_de( struct dirent *de, char *dir, char *pattern, char type )
{
char fn[ _POSIX_PATH_MAX ];
strcpy(fn, dir);
strcat(fn, "/");
strcat(fn, de->d_name);
if ( access(fn, (R_OK | X_OK)) == 0 )
{
struct stat buf;
lstat(fn, &buf);
//check pattern matches, etc., printf fn if appropriate
if ( ( S_ISDIR(buf.st_mode) ) &&
( strcmp(de->d_name, ".") != 0 ) &&
( strcmp(de->d_name, "..") != 0 ) )
open_dir(fn, pattern, type);
}
return;
}
【问题讨论】: