Search code examples
c++stat

C++ - What permissions does stat() need?


I've got some problems using the stat() function.

What I'm doing is very simple, and I remember it worked on another machine.
I have a directory structure like this:
/home/bernd/dir /home/bernd/dir/file.ext /home/bernd/dir/anotherDir and so on...
What I want to do is to distinguish between files and directories with this source code:

    DIR *dir = opendir("/home/bernd/dir");
    struct dirent *pent;

    while(pent = readdir(dir))
    {
      if((strcmp(pent->d_name,".") == 0) || (strcmp(pent->d_name,"..") == 0)
        continue;

      struct stat st;
      string tmp = "/home/bernd/dir/" + pent->d_name;
      if(stat(tmp.c_str(),&st) == -1)
        cout<<strerror(errno);
      else
        //would be happy to get here
    }

As you can see I'm simply walking through the directory and calling stat on the current element, but the stat call always returns Permission Denied. I thought I was messing with relative paths at first, or I was calling stat on the wrong path, which is kept in the string tmp, but I checked them and everything was fine.

The next thing was of course to change the permissions of the files and directories, so anyone can read and write, but the result did not change.

I really hope you guys can help me in any way and your help is highly appreciated!
Thank you in advance!


Solution

  • Do you have execute permission to /home/bernd/dir? Read permission only allows you to list the directory without necessarily being able to access any of its contents.

    (On the other hand, execute permission without read permission lets you access the contents but makes the directory unlistable (readdir would fail).)