Just starting to learn some basic C and messing around with the stat() system call on Linux.
So st_mode returned in the struct from stat() is a bitfield. And I can get the octal permissions by simply printf("octal %o", st.st_mode) but I’m only interested in certain flags in the bitfield, namely S_IRWXU, S_IRWXG and S_IRWXO to send that value to another function, eg: mkdir.
Here’s my sample program.
Ignore the fact that this is a rubbish program with the directories hard-coded, not passed as an argument to the create_dir() function and with no error checking.
#include <stdio.h>
#include <sys/stat.h>
static int create_dir(mode_t mode) {
mkdir("/home/user/blahnew", mode);
}
main() {
struct stat st;
int res;
res = stat("/home/user/blah", &st);
printf("user %o\n", st.st_mode & S_IRWXU);
printf("group %o\n", st.st_mode & S_IRWXG);
printf("other %o\n", st.st_mode & S_IRWXO);
create_dir(mode);
return 0;
}
How can I take only the above flages in st.st_mode and pass it as an octal to create_dir() to be used by an mkdir() function?
If I just did create_dir(st.st_mode) would that not also pass all the other flags that mkdir() doesn’t need… uid, gid, sticky bit etc?
Cheers, B
You already did 99% of the work in your code. When you say
only the bits in
st.st_modethat are present in theS_IRWXUbitmask remain. So what you want is a different bitmask that combines the other three: