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: %s\n", direntp->d_name);
printf("Stat Call Error\n");
exit(-1);
}
printf("Success: %s\n", direntp->d_name);
}
}
closedir(dirp);
return 0;
}