这个问题在这里已有答案:
我正在尝试使用stat()列出文件信息(包括目录等)
当我将“ . ”(当前目录)作为argv [1](例如$ . / a.out . )时,它工作正常 .
但是当我给出其他目录如“..”,“/”等时出错 .
在direntp指向“..”(父目录)之后,stat函数返回-1(失败) .
这是一个例子 .
$ ls -a ..
. .. sample temple
$ ./a.out ..
Success: .
Success: ..
Fail: sample
Stat Call Error.
Terminate.
$
那么为什么当我给stat()的参数提供其他路径时它会失败?
这是我的代码如下
#include "stdio.h"
#include "dirent.h"
#include "sys/stat.h"
#include "unistd.h"
#include "stdlib.h"
int main(int argc, char const *argv[])
{
DIR *dirp;
struct dirent *direntp;
struct stat statbuf;
dirp = opendir(argv[1]);
while((direntp = readdir(dirp)) != NULL)
{
if(direntp->d_ino == 0)
continue;
if(direntp->d_name[0] != '.'); /* doesn't matter, This isn't a mistake */
{
if(stat(direntp->d_name, &statbuf) == -1)
{
printf("Fail: %s\n", direntp->d_name);
printf("Stat Call Error\n");
exit(-1);
}
printf("Success: %s\n", direntp->d_name);
}
}
closedir(dirp);
return 0;
}
1 回答
opendir
函数使用相对路径返回目录内容,而不是绝对路径 .当您不扫描当前目录时,您只有该条目的名称,但不是其完整路径,因此
stat
在所有条目上都失败,因为它在当前目录中查找它们(但是.
和..
也存在于当前目录中)当前目录) .当然它可以在当前目录中工作,在那里你没有这个问题 .
修复:编写完整路径名,例如: