Search code examples
c++linuxfilemodestat

Get owner's access permissions using C++ and stat


How can I get the file owner's access permissions using stat from sys/stat.h using C++ in Kubuntu Linux?

Currently, I get the type of file like this:

  struct stat results;  

  stat(filename, &results);

  cout << "File type: ";
  if (S_ISDIR(results.st_mode))
    cout << "Directory";
  else if (S_ISREG(results.st_mode))
    cout << "File";
  else if (S_ISLNK(results.st_mode))
    cout << "Symbolic link";
  else cout << "File type not recognised";
  cout << endl;

I know I should use t_mode's file mode bits, but I don't know how. See sys/stat.h


Solution

  •   struct stat results;  
    
      stat(filename, &results);
    
      cout << "Permissions: ";
      if (results.st_mode & S_IRUSR)
        cout << "Read permission ";
      if (results.st_mode & S_IWUSR)
        cout << "Write permission ";
      if (results.st_mode & S_IXUSR)
        cout << "Exec permission";
      cout << endl;