Get owner access permissions using C ++ and stat

How can I get the permissions on file owners using stat from sys / stat.h using C ++ in Kubuntu Linux?

I am currently getting the file type 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 be using the mode bits of the t_mode file, but I don't know how. See sys / stat.h

+2


source to share


2 answers


  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;

      



+7


source


Owner permission bits are set by a macro S_IRWXU

from <sys/stat.h>

. The value will be multiplied by 64 (0100 octal), therefore:

cout << "Owner mode: " << ((results.st_mode & S_IRWXU) >> 6) << endl;

      



This will print a value between 0 and 7. There are similar masks for group ( S_IRWXG

) and others ( S_IRWXO

) with offsets of 3 and 0 respectively. There are also separate masks for each of the 12 separate bits of resolution.

+1


source







All Articles