源码

首页 » 归档 » 源码 » c – 为什么stat使用readdir中的名称失败?

c – 为什么stat使用readdir中的名称失败?


我写了一个打印目录名或文件名的程序.这很容易,但我遇到了麻烦.
它无法区分目录和文件类型.我知道,我用stat.st_mode来完成它.但有些事情是错的:

enter image description here

当我使用gdb检查st_mode值时,我发现它是0,除了“.”和“..”,所以这里有一个问题:为什么st_mode为0?

那是我的代码:

#include 
#include 
#include 
#include 

int main(void)
{
    DIR *pDir = opendir("MyDirectory");
    struct dirent *pDirent;
    struct stat vStat;

    if (pDir == NULL)
    {
        printf("Can't open the directory /"MyDirectory/"");
        exit(1);
    }

    while ((pDirent = readdir(pDir)) != NULL)
    {
        stat(pDirent->d_name, &vStat);
        if (S_ISDIR(vStat.st_mode))
            printf("Directory: %s/n", pDirent->d_name);
        else
            printf("File: %s/n", pDirent->d_name);
    }

    closedir(pDir);
    return 0;
}
(0)

本文由 投稿者 创作,文章地址:https://blog.isoyu.com/archives/c-weishenmestatshiyongreaddirzhongdemingchengshibai.html
采用知识共享署名4.0 国际许可协议进行许可。除注明转载/出处外,均为本站原创或翻译,转载前请务必署名。最后编辑时间为:9 月 16, 2019 at 11:48 上午

热评文章