为什么 stat 使用 readdir 中的名称失败? [英] Why does stat fail using a name from 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
", pDirent->d_name);
else
printf("File: %s
", pDirent->d_name);
}
closedir(pDir);
return 0;
}
推荐答案
Classic 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屋!