为什么stat使用readdir中的名称失败? [英] Why does stat fail using a name from readdir?

查看:121
本文介绍了为什么stat使用readdir中的名称失败?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编写了一个打印目录名或文件名的程序.很简单,但是我遇到了麻烦. 它无法区分目录和文件类型.我知道,我用stat.st_mode完成了.但是出了点问题:

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:

当我使用gdb检查st_mode值时,我发现它是0,除了".和"..",所以这里是一个问题:为什么st_mode为0?

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?

那是我的代码:

#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下.

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.

检查stat的返回值.您会看到它是ENOENT-除了...之外,它们也存在于当前目录中.当stat失败时,stat结构的内容未定义.

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.

如果要在.以外的目录中调用opendir,则要对返回的名称执行几乎所有有用的操作,您需要构建完整路径.将传递给opendir的路径复制到缓冲区,该缓冲区具有足够的空间以容纳斜杠和文件名,然后将每个文件名复制到该缓冲区.概念验证代码(省略了错误检查等):

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

这篇关于为什么stat使用readdir中的名称失败?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆