我写了一个程序打印目录名或文件名。这很容易,但我有点麻烦。
它无法区分目录和文件类型。我知道,我用stat.st_模式来完成它。但有点不对劲:
c - 为什么stat使用readdir中的名称失败?-LMLPHP
当我使用gdb检查st_mode值时,我发现它是0,除了“.”和“..”,所以这里有一个问题:为什么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;
}

最佳答案

经典错误:readdir是目录项的名称,而不是文件的路径。它是pDirent->d_name,"1"等,所以您的"4-5.c"调用会在当前目录中查找具有该名称的文件,而不是在stat下。
检查MyDirectory的返回值。除了当前目录中存在的stat和ENOENT之外,您将看到它是>。当.失败时,stat结构的内容是未定义的。
如果您在..以外的目录中调用stat,那么要对返回的名称执行任何有用的操作,您需要构建一个完整的路径。将您传递到opendir的路径复制到一个缓冲区,该缓冲区有足够的空间容纳斜杠和文件名,并将每个文件名复制到该缓冲区。概念验证代码(省略错误检查等):

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

关于c - 为什么stat使用readdir中的名称失败?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/36416033/

10-13 07:44