Reputation: 31604
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
Upvotes: 2
Views: 13322
Reputation: 30449
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;
Upvotes: 7
Reputation: 755006
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.
Upvotes: 1