Q: How to get octal chmod format from stat() in c 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.

A: 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. %o will print it as an octal number.
However, st_mode will get you a whole lot more information. (Hence the 100 at the start.) You'll want to use the S_IRWXU (rwx information of the "user"), S_IRWXG (group) and S_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:
struct stat buf;  
stat(filename, &buf);
int statchmod = buf.st_mode & (S_IRWXU | S_IRWXG | S_IRWXO);
printf("chmod: %o\n", statchmod);

Resources:


*

*More about format identifiers

*Related constants

A: I like @ilias answer. However, if you're like me and actually want the full chmod value (such as for saving and restoring original file permissions completely), then this routine would do it, and would ensure leading zeroes are not lopped off either.
static std::string getChmodPerms(std::string sFile) {
    struct stat buf;
    stat(sFile.c_str(),&buf);
    int statchmod = buf.st_mode;
    char mybuff[50];
    sprintf(mybuff,"%#o",statchmod);
    std::string sResult(mybuff);
    return sResult;
}

It's C++, but it's trivial to convert to C if you want.
