I am having some trouble counting only the regular files in a directory.
This is my code:
int show_regular_files(char ** path) {
DIR * dp = opendir(*path); // open the path
char d_path[BUFSIZE]; //
struct dirent *ep;
struct stat sb;
int number=0;
int rv;
if (dp != NULL){
while (ep = readdir (dp)){
sprintf(d_path,"%s/%s ",*path,ep->d_name);
rv= stat(d_path, &sb);
if(rv<0)
continue;
else{
if((sb.st_mode & S_IFMT)==S_IFREG){ // checks if a file is regular or not
if(sb.st_mode & S_IXOTH || sb.st_mode & S_IXGRP){// search permission & group owner of the file
number++;
}
}
}
}
}
else
perror("can't open the file ");
closedir(dp); // finally close the directory
return number;
}
It always prints 0 unless I remove the REGULARFILE condition check and stat line, then it lists all the files in the directory.
I think the problem is in this line:
sprintf(d_path,"%s/%s ",*path,ep->d_name);
^
where you have an extra space at the end which results in stat()
calls failing. You need to remove that space.
By the way, avoid sprintf()
. Use snprintf()
instead.