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

功能很简单,列出当前给定目录"MyDirectory"里的文件和文件夹,就第一层深度。

clipboard.png

clipboard.png
用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;
}
阅读 4.8k
2 个回答

答案在于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");
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题