Unks
Unks

Reputation: 128

extracting digits from octal number in C

Im trying to get the file permissions for a file or directory using the function stat(). I can get the correct information, such as; st_nlinks is for number of hard links and st_mode gives the mode of the file, which is what I am looking for. But the value stores in st_mode is an octal number. How do I now extract just the owner permissions.

For example the st_mode might store 42755 which means the owner has read write and execution permissions, but I don't know how to get extract the 7 from the number. If this is confusing maybe my code below will clarify things.

CODE:

DIR *dirp;
struct dirent *dp;
struct stat buf;

dirp = opendir(".");
while ((dp = readdir(dirp)) != NULL){
   stat(dp->d_name, &buf);

   //now here I have the octal number for the file permissions
   //If I put a print statement here like so:
   printf(">> %o %s\n", buf.st_mode, dp->d_name);
}

So some of you may see that I am trying to do what ls -l does on a Unix system. So instead of printing out the octal number for the mode I want to convert it to something like:

drwxr-xr-x for the value stored in st_mode: 42755

My professor recommended using a mask and perform a bitwise operation on it. I understand what he means but I tried something like:

mode_t owner = 0000100 & st_mode;

But when I print out owner I get the value of 100.

printf(">> owner permission: %o\n", owner);

OUTPUT:

owner permission: 100

So I am confused on how to do this. Does anyone know how to solve this problem?

By the way in case anyone is wondering I use mode_t as the type for owner because according to the man page for stat (man 2 stat) the member variable st_mode of the stat structure is of type mode_t. I figure this is just like a long int or something.

Upvotes: 2

Views: 824

Answers (3)

Vicctor
Vicctor

Reputation: 833

You should consider using defined macros rather than trying to "parse" permissions manually. Let's say you wish to get the write permission for the file owner user, that could be checked like this:

int wpo = buff.st_mode & S_IWUSR;
if (wpo) {
  printf("Owner has write permission");
} else {
  printf("Owner doesn't have write permission");
}

You will find more useful macros in the documentation for "sys/stat.h": http://pubs.opengroup.org/onlinepubs/009695399/basedefs/sys/stat.h.html

Upvotes: 2

Ali ISSA
Ali ISSA

Reputation: 408

The mask must be 0700: 111 000 000 To get owner rights rwx

Upvotes: 1

vmt
vmt

Reputation: 860

Use the macros defined in sys/stat.h to resolve the mode bits.

Refer to: http://www.johnloomis.org/ece537/notes/Files/Examples/ls2.html function mode_to_letters() for implementation details.

Upvotes: 1

Related Questions