我正在尝试通过所有子目录搜索给定参数的文件。我的代码问题在于,当它到达一个不是目录的文件时,它会停止并显示“打开目录错误”的错误信息。
我找不到解决方法。我尝试了另一个
我找不到解决方法。我尝试了另一个
if(S_ISREG...)
,但它没有起作用。include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <dirent.h>
#include <string.h>
void check_file_existence(char *dirName,char *file){
struct stat *metadata;
char name[1000];
struct dirent *dirEntry;
struct stat bufstat;
DIR *dir;
dir = opendir(dirName);
if (dir==NULL)
{
perror("Error opening the directory\n");
exit(1);
}
while ((dirEntry = readdir(dir))!=NULL){
lstat(dirEntry->d_name,&bufstat);
if(S_ISDIR(bufstat.st_mode)){
if (strcmp(dirEntry->d_name,".")==0 || strcmp(dirEntry->d_name,"..")==0){
continue;
}
sprintf(name,"%s/%s",dirName,dirEntry->d_name);
printf("%s\n",name);
check_file_existence(name,file);
}
}
closedir(dir);
}
int main(int argc,char **argv){
if (argc!=3){
perror("Number of arguments is wrong.\n");
exit(1);
}
check_file_existence(argv[1],argv[2]);
}
readdir
之后,如果你调用stat(dirEntry->d_name)
通常会失败,因为d_name
只是该条目的名称,而不是其路径。通常在dirName
路径和d_name
之间进行连接才能进行状态检查。这是一个容易犯的错误,也是一个经常被问到的问题:参见为什么在调用readdir后无法使用stat?。 - Steve Summitlstat
调用。如果您阅读 readdir 手册页面,您将会看到dirent
结构体有一个d_type
成员,它会告诉您该文件是否为目录。附带地,这也将解决您的问题(或者从lstat
调用中检查错误,而您应该始终这样做)。 - Some programmer dudedirName
和d_name
。如果您早些时候在调用lstat
之前这样做,您的原始程序可能会正常工作。(不过,当您调用l/stat时,应该检查错误,就像Some programmer dude提到的那样。) - Steve Summit