I need to know how to get file permissions in octal format and save it to an int. I tried something like this:
struct stat buf;
stat(filename, &buf);
int statchmod = buf.st_mode;
printf("chmod: %i\n", statchmod);
But he output was:
chmod: 33279
and should be 777.
33279 is the decimal representation of the octal 100777. You get a decimal representation because you requested the number to be printed as a decimal, through the format identifier
%i.%owill print it as an octal number.However, st_mode will get you a whole lot more information. (Hence the
100at the start.) You’ll want to use theS_IRWXU(rwx information of the “user”),S_IRWXG(group) andS_IRWXO(other) constants to get the permissions for the owner, group and other figured out. These are respectively defined at 700, 070 and 007, all in octal representation. OR’ing these together and filtering out the specified bits using AND will yield you only the data you want.The final program hence becomes something like this:
Resources: