开发者社区> 问答> 正文

为什么有的文件stat结构的st_mode为0?

功能很简单,列出当前给定目录"MyDirectory"里的文件和文件夹,就第一层深度。
screenshot
用gdb看了下,有些st_mode为0,请问为什么呢?

#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <sys/stat.h>

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;
}

展开
收起
a123456678 2016-06-23 15:18:56 2865 0
1 条回答
写回答
取消 提交回答
  • 答案在于stat调用失败!根据返回的errno表示没有这个文件或文件夹。
    因为目前还是在当前目录,而不是在"MyDirectory"下。所以文件路径pathname就不存在。
    解决方法有二:
    一是在将MyDictory的名字也加进来:

    char *directory = "MyDirectory";
    size_t directory_length = strlen(directory);
    char *path = malloc(directory_length + 1 + NAME_MAX);
    strcpy(path, directory);
    path[directory_length] = '/';
    while ((pDirent = readdir(pDir)) != NULL) {
        strcpy(path + directory_length + 1, pDirent->d_name);
        if (stat(path, &vStat) == -1) {
            perror(path);
            continue;
        }
        …
    }
    二是进入该目录:
    
    chdir("MyDictory");
    2019-07-17 19:46:24
    赞同 展开评论 打赏
问答分类:
问答地址:
问答排行榜
最热
最新

相关电子书

更多
Spark SQL: Past, Present and Future 立即下载
Spark SQL:Past Present &Future 立即下载
OPEN SOURCE IN A DATA-DRIVEN WORLD 立即下载