Crylvarrey
Crylvarrey

Reputation: 109

stat() failed : No such file or directory

I want to get list of files and folders with permissions etc. but for every item I'm getting stat error "No such file or directory" and list contains only items "." and ".."

Code:

list<string> res;
DIR *dirp;
dirp = opendir("/");
struct dirent *dp;
while ((dp = readdir(dirp)) != NULL){
    stringstream ss;
    struct stat fileStat;
    if(stat(dp->d_name, &fileStat) < 0)    {
        std::cout << "stat() failed: " << std::strerror(errno) << "(" << dp->d_name << ")" << endl;
        continue;
    }


    ss << ( (S_ISDIR(fileStat.st_mode)) ? "d" : "-" )
     << ( (fileStat.st_mode & S_IRUSR) ? "r" : "-")
     << ((fileStat.st_mode & S_IWUSR) ? "w" : "-")
     << ((fileStat.st_mode & S_IXUSR) ? "x" : "-")
     << ((fileStat.st_mode & S_IRGRP) ? "r" : "-")
     << ((fileStat.st_mode & S_IWGRP) ? "w" : "-")
     << ((fileStat.st_mode & S_IXGRP) ? "x" : "-")
     << ((fileStat.st_mode & S_IROTH) ? "r" : "-")
     << ((fileStat.st_mode & S_IWOTH) ? "w" : "-")
     << ((fileStat.st_mode & S_IXOTH) ? "x" : "-") << "\t"
     << fileStat.st_nlink << "\t"
     << fileStat.st_uid << "\t"
     << fileStat.st_gid << "\t"
     << fileStat.st_size << "\t";

    char mbstr[100];
    time_t t = (time_t)fileStat.st_mtim.tv_sec;        
    struct tm *tminfo = localtime ( &t );
    strftime(mbstr, sizeof(mbstr), "%b %d %H:%M", tminfo  );
    ss << mbstr << "\t"
       << dp->d_name;
    res.push_back(ss.str());
}

for( string s : res ){
    cout << s << endl;
}

Result:

...
stat() failed: No such file or directory(usr)
stat() failed: No such file or directory(var)
stat() failed: No such file or directory(home)
stat() failed: No such file or directory(etc)
stat() failed: No such file or directory(bin)
drwxrwxr-x      9       1000    1000    4096    May 29 02:08    .
drwxrwxr-x      3       1000    1000    4096    Mar 16 22:36    ..

The example above is for root "/" and I have tried lots of directories but the error does not occur only for current directory ".".

Can you tell me please how to avoid this problem? Thanks!

Upvotes: 1

Views: 4494

Answers (1)

quantdev
quantdev

Reputation: 23793

You are executing stat() on a directory name, not on a path. i.e. you are executing it on "usr" instead of "/usr"

To avoid your problem, make sure to call stat on a path (that your while loop will probably build)

Upvotes: 1

Related Questions