[英]S_ISREG not working on listing function
我在僅計算目錄中的常規文件時遇到了一些麻煩。
這是我的代碼:
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 條件檢查和 stat 行,然后它列出目錄中的所有文件。
我認為問題出在這一行:
sprintf(d_path,"%s/%s ",*path,ep->d_name);
^
最后有一個額外的空間會導致stat()
調用失敗。 您需要刪除該空間。
順便說一下,避免使用sprintf()
。 請改用snprintf()
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.