what's wrong with my stat() function in C in linux
I'm trying to list file infos(including directories etc) using stat()
It works fine when I give "."(current directory) as argv[1] (ex. $./a.out .)
but has an error when I give other directory such as "..", "/" etc.
stat function returns -1(fail) when after direntp points ".."(parent directory).
here's an example.
$ ls -a ..
. .. sample temple
$ ./a.out ..
Success: .
Success: ..
Fail: sample
Stat Call Error.
Terminate.
$
So why does it fail when I give other path to argument of stat()?
here's my code below
#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; }
The opendir
function returns directory contents using relative path, not absolute.
When you're not scanning the current directory, you only have the name of the entry, but not its full path, so stat
fails on all entries because it looks them up in the current directory (but .
and ..
which also exist in the current directory).
Of course it works in the current directory, where you don't have this problem.
Fix: compose the full pathname, ex like this:
char fp[PATH_MAX];
sprintf(fp,"%s/%s",argv[1],direntp->d_name);
if(stat(fp, &statbuf)) {
...
链接地址: http://www.djcxy.com/p/85956.html
上一篇: 内存分配/释放瓶颈?