首页 > 解决方案 > S_ISDIR 不能过滤是否是目录

问题描述


void my_double_ls(char *dirname)
{
    struct dirent *d;
    struct stat statbuf;
    DIR *dp;
    if ((dp = opendir(dirname)) == NULL)
        exit(1);

    while ((d = readdir(dp)) != NULL)
    {
        if (d->d_ino != 0)
        {
            d->d_name[d->d_namlen] = 0;
            if (stat(d->d_name, &statbuf) == -1)
            {
                printf("%s %d %d %d\n", d->d_name, S_ISDIR(statbuf.st_mode), S_ISREG(statbuf.st_mode), d->d_namlen);

            }
            else
            {
                if (S_ISDIR(statbuf.st_mode))
                {
                    printf("%s *\n", d->d_name);
                }
                else
                {
                    printf("%s\n", d->d_name);
                }
            }
        }
    }

    closedir(dp);
}

int main(int argc, char *argv[])
{
    if (argc != 2)
    {
        printf("wrong argument numbers\n");
        exit(1);
    }
    my_double_ls(argv[1]);
    return 0;
}

我是这样写的,但是当我插入文件名并检查stat function
所有 stat 的 d(dirent) 名称的返回值是否为 -1 并且 S_ISDIR 始终为真时,即使存在 txt 文件,这有什么问题?

标签: cunix

解决方案


推荐阅读