Why can't stat use name from readdir?

I wrote a program that prints a directory name or file name. It’s easy, but I’m having problems. He could not distinguish between directory and file type. I know, and I used stat.st_mode to finish this. But something is wrong

enter image description here

When I use gdb to check the st_mode value, I find that it was 0 except for "." and "..", so this is the question: why is st_mode equal to 0?

and this 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;
}
0
source share
1 answer

Classic error readdir: pDirent->d_nameis the name of the entry in the directory, not the path to the file. This "1", "4-5.c"etc. So your calls statare looking for a file with that name in the current directory, not under MyDirectory.

stat. , ENOENT - . .., . stat , stat undefined.

opendir , ., , - , . , 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;
    }
}
+5

Source: https://habr.com/ru/post/1695006/


All Articles