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 in int. I tried something like this:

struct stat buf; stat(filename, &buf); int statchmod = buf.st_mode; printf("chmod: %i\n", statchmod); 

But he deduced:

 chmod: 33279 

and should be 777.

+4
source share
2 answers

33279 is the decimal notation of the octal 100777. You get the decimal notation because you requested the number to be printed as decimal using the format identifier %i . %o will print it as an octal number.

However, st_mode will give you much more information. (Therefore, 100 at the beginning.) You will want to use S_IRWXU (rwx information for the user), S_IRWXG (group) and S_IRWXO (other) constants to get permissions for the owner, group and others. They are defined respectively in 700, 070 and 007, all in octal representation. OR, combining them together and filtering out the specified bits using AND, you will only get the data you need.

The last program, thus, 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

+6
source

I like @ilias answer. However, if you are like me and really want to get the full chmod value (for example, to save and restore the original file permissions completely), then this procedure will do this and will guarantee that leading zeros will not be disabled 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; } 

This is C ++, but it is trivial to convert to C if you want.

0
source

All Articles