I am writing a program which searches through all the sub-directories of a given directory. The problem is, is that I know the name of the file that I am looking for (data.txt) but I still need to know all of the (possibly multiple) locations where the file is. I am using this code to search:
struct dirent *dp;
struct stat s;
DIR *dir;
char path[]="/some/path/here/";
if((dir=opendir(path))==NULL){return;}
while((dp=readdir(dir))!=NULL){
char *temp=malloc((strlen(path)+strlen(dp->d_name)+4)*sizeof(*temp));
sprintf(temp,"%s%s",path,dp->d_name);//concatenate path
lstat(temp,&s);//stat the path
if(S_ISREG(s.st_mode)){//if regular file
if(!strcmp(dp->d_name,"data.txt")){
printf("found one: %s\n",temp);//found the target file
}
}else if(S_ISDIR(s.st_mode) && !S_ISLNK(s.st_mode)){//if directory, but not symlink
if(strcmp(dp->d_name,".") && strcmp(dp->d_name,"..")){//ignore "." and ".."
//recurse on the subdirectories
}
}
free(temp);
}
closedir(dir);
The code works fine and its still very fast, but I still feels that it's very inefficient to be lstat
-ing every file/directory in the filesystem just to look for directories.
Is there a more efficient way of searching so that only directories are returned via readdir
?
I'm using gcc on Fedora 13