Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get octal chmod format from stat() in c

Tags:

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.

like image 360
user1827257 Avatar asked Jan 14 '13 19:01

user1827257


People also ask

How do I find my octal permissions?

You need to use the stat command to view or get octal file permissions for given filename. By default the ls command will not display the permissions on a file in octal form. The permission in octal form is useful for many commands such as chmod command and other sysadmin tasks.

How do I get permission from statistics?

Check file Permissions with stat command in Linux To use “stat”, simply type “stat filename” at the command prompt. This will give you a detailed output of all the permissions for the file. Device: fd01h/64769d Inode: 262094 Links: I-Node uid=1001(user) gid=1001(user) mode=0644(rw-r–r–) . . .

What is chmod octal file?

What does it do? chmod command is used to change permissions of a given file according to a certain mode which might be a set of octal characters or a set of alphabetical characters. Permissions explained. Each file on your system has a certain set of permissions associated with it.


1 Answers

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:

  1. More about format identifiers
  2. Related constants
like image 109
ilias Avatar answered Oct 19 '22 03:10

ilias