gpt4 book ai didi

c - S_ISREG 不适用于列表功能

转载 作者:太空宇宙 更新时间:2023-11-04 03:24:52 25 4
gpt4 key购买 nike

我在仅计算目录中的常规文件时遇到了一些问题。

这是我的代码:

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);
^

最后有一个额外的空格会导致 stat() 调用失败。您需要删除该空格。

顺便说一句,避免sprintf()。请改用 snprintf()

关于c - S_ISREG 不适用于列表功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41968916/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com