我的linux中的stat()函数有什么问题
我试图用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: %sn", direntp->d_name);
printf("Stat Call Errorn");
exit(-1);
}
printf("Success: %sn", direntp->d_name);
}
}
closedir(dirp);
return 0;
}
opendir函数使用相对路径返回目录内容,而不是绝对路径。
当你不扫描当前目录下,你只有条目的名称,而不是它的完整路径,因此stat上的所有条目失败,因为它看起来他们,在当前目录(但是.和..这也存在于当前目录)。
当然,它在当前目录中工作,在那里你没有这个问题。
修复:编写完整的路径名,例如:
char fp[PATH_MAX];
sprintf(fp,"%s/%s",argv[1],direntp->d_name);
if(stat(fp, &statbuf)) {
...
链接地址: http://www.djcxy.com/p/85955.html
