S_ISREG 无法使用列表功能
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;
}
除非我删除 REGULARFILE 条件检查和统计行,否则它总是打印 0,然后它会列出目录中的所有文件。
我认为问题出在这一行:
sprintf(d_path,"%s/%s ",*path,ep->d_name);
^
最后有一个额外的 space,导致 stat()
调用失败。您需要删除 space.
顺便说一句,避免sprintf()
。请改用 snprintf()
。
我在仅计算目录中的常规文件时遇到一些问题。
这是我的代码:
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;
}
除非我删除 REGULARFILE 条件检查和统计行,否则它总是打印 0,然后它会列出目录中的所有文件。
我认为问题出在这一行:
sprintf(d_path,"%s/%s ",*path,ep->d_name);
^
最后有一个额外的 space,导致 stat()
调用失败。您需要删除 space.
顺便说一句,避免sprintf()
。请改用 snprintf()
。