views:

935

answers:

2

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

A: 

The owner permission bits are given by the macro S_IRWXU from <sys/stat.h>. The value will be multiplied by 64 (0100 octal), hence:

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

This will print out a value between 0 and 7. There are similar masks for group (S_IRWXG) and others (S_IRWXO), with shifts of 3 and 0 respectively. There are also separate masks for each of the 12 individual permission bits.

Jonathan Leffler
+4  A: 
  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;
drhirsch