如何获取目录中的目录数? [英] how can I get the number of directories in a directory?
本文介绍了如何获取目录中的目录数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试获取目录中的目录数,但我无法获得真实的结果。如果目录中有5个文件,其中2个是目录,我得到''y''5但它必须是2.
x = isdirectory(dirp);我不确定是否将相关内容发送给函数。谢谢。
I am trying to get the number of directories in a directory but I cannot get the real result. If there are 5 files in directory and 2 of them are directories, I get ''y'' 5 but It must be 2.
x= isdirectory(dirp); I am not sure whether I send the corrent thing to the function.Thanks in advance.
int listFilesIndir(char *currDir) //Lists files in directory
{
struct dirent *direntp;
DIR *dirp;
int x ,y =0 ;
if ((dirp = opendir(currDir)) == NULL)
{
perror ("Failed to open directory");
return 1;
}
while ((direntp = readdir(dirp)) != NULL)
{
printf("%s\n", direntp->d_name);
x= isdirectory(dirp); //I dont not know what I should send to the function
// to check if its directory or not? it must
// be ''dirp'' or ''d_name''? what?
if(x != 0)
y++;
}
printf("direc Num : %d\n",y );
while ((closedir(dirp) == -1) && (errno == EINTR)) ;
return 0;
}
int isdirectory(char *path)
{
struct stat statbuf;
if (stat(path, &statbuf) == -1)
return 0;
else
return S_ISDIR(statbuf.st_mode);
}
推荐答案
我发现了问题。现在效果很好。 if statemenet已更新。
I have found the problem .Now It works great. The if statemenet is updated.
int listFilesIndir(char *currDir)
{
struct dirent *direntp;
DIR *dirp;
int x ,y =0 ;
if ((dirp = opendir(currDir)) == NULL)
{
perror ("Failed to open directory");
return 1;
}
while ((direntp = readdir(dirp)) != NULL)
{
printf("%s\n", direntp->d_name);
if(direntp->d_type == DT_DIR) //Updated..
y++;
}
printf("direc Num (except parent and curr) : %d\n",y-2 );
while ((closedir(dirp) == -1) && (errno == EINTR)) ;
return 0;
}
这篇关于如何获取目录中的目录数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文