S_ISREG не работает над функцией листинга
У меня возникли проблемы с подсчетом только обычных файлов в каталоге.
Это мой код:
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;
}
Он всегда печатает 0, если я не удаляю проверку условий REGULARFILE и строку статистики, затем перечисляет все файлы в каталоге.
1 ответ
Решение
Я думаю, что проблема в этой строке:
sprintf(d_path,"%s/%s ",*path,ep->d_name);
^
где у вас есть дополнительное место в конце, что приводит к stat()
звонки сбой. Вы должны удалить это место.
Кстати, избегайте sprintf()
, использование snprintf()
вместо.