Why does stat fail using a name from readdir?

旧巷老猫 提交于 2019-11-26 03:45:45

问题


I wrote a program that print the directory name or file name. It\'s easy but I got something trouble. It couldn\'t distinguish directory and file type. I know and I used stat.st_mode to finish it. But something is wrong:

When I use gdb to check the st_mode value, I found it was 0, except \".\" and \"..\", so here is the question: why st_mode is 0?

and that is my code:

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

回答1:


Classic readdir mistake: pDirent->d_name is the name of the directory entry, not a path to the file. It's "1", "4-5.c", etc. So your stat calls are looking for a file with that name in the current directory, not under MyDirectory.

Check the return value of stat. You'll see that it's ENOENT — except for . and .., which exist in the current directory as well. When stat fails, the content of the stat structure is undefined.

If you're calling opendir in a directory other than ., then to do pretty much anything useful with the returned names, you need to build a full path. Copy the path you passed to opendir to a buffer with enough room for a slash and file name in addition, and copy each file name to that buffer. Proof-of-concept code (error checking omitted, etc.):

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


来源:https://stackoverflow.com/questions/34168266/why-does-stat-fail-using-a-name-from-readdir

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!