c - 如何获取目录中的目录数?

标签 c linux unix system

我正在尝试获取文件夹中除文件外的目录数,但我无法获得正确的结果。有人帮我解决这个问题吗?特别是我应该向 isDirectory() 函数发送什么?

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);
        x= isDirectory(dirp);
        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);
}

最佳答案

您正在向函数发送目录流,并将其视为路径。

Linux 和其他一些 Unix 系统包含一种直接获取此信息的方法:

while ((direntp = readdir(dirp)) != NULL)
{
    printf("%s\n", direntp->d_name);
    if (direntp->d_type == DT_DIR)
       y++;
}

否则,请确保向函数发送正确的详细信息,即

x= isDirectory(direntp->d_name);

关于c - 如何获取目录中的目录数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15751311/

相关文章:

typedef (timer_t) 的冲突类型错误

python - 使用单个 Python 脚本从 Linux、Mac 和 Windows 上的剪贴板复制数据

Bash - 压缩后丢失新行字符

c - 将 const 变量的地址分配给非 const 指针

c - 将指针从一个函数传递到另一个函数

c - 检索文件中的总行号

c - 使用硬编码内存地址主机测试 C 程序

java - 是否可以在没有官方 oracle dmg 文件的情况下在 mac os x 上安装 JDK 7 或 8?

unix - 从类型中选择的结构成员,它是不可见的,不会被选中

bash - sed - 在进行替换后从列出的值中删除最后一个逗号