Smi*_*ohn 0 c linux file readdir
我写了一个打印目录名或文件名的程序.这很容易,但我遇到了麻烦.它无法区分目录和文件类型.我知道,我用stat.st_mode来完成它.但有些不对劲:

当我使用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;
}
Run Code Online (Sandbox Code Playgroud)
经典readdir错误:pDirent->d_name是目录条目的名称,而不是文件的路径.它是"1","4-5.c"等等.所以你的stat调用是在当前目录中寻找具有该名称的文件,而不是在MyDirectory.
检查返回值stat.你会看到它ENOENT- 除了.和..当前目录中存在的和.当stat出现故障时,stat结构的内容是不确定的.
如果你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;
}
…
}
Run Code Online (Sandbox Code Playgroud)