Bhargava Mourya
Bhargava Mourya

Reputation: 13

fchmod() unable to apply file permissions correctly in C

This is the partial code where I am trying to apply permissions to file.

fd=fopen(file_name,"wb");
fchmod(fd,(mode_t)perm);

Where perm is an integer . ex: 644 or 755 I tried without casting with mode.

Upvotes: 0

Views: 920

Answers (3)

Paul R
Paul R

Reputation: 212969

Apart from the already-mentioned issue of using octal constants, you are calling fchmod incorrectly - the prototype is:

 int
 fchmod(int fildes, mode_t mode);
        ^^^^^^^^^^

but you are passing a FILE * (as returned by fopen) for the first parameter! Either use open instead of fopen, so that you get an int fildes to play with, or use chmod with the file name.

There are two important take-home message here:

  1. you should always enable compiler warnings, and take heed of any warnings. If you had done this then it would have been immediately obvious that you were calling fchmod incorrectly.

  2. calls like fchmod return a status - you should not ignore this! It will most likely be non-zero in your case, as you passed an invalid fildes parameter. So even if the code had been correct, you would still have learned something from the non-zero status.

Upvotes: 2

wallyk
wallyk

Reputation: 57774

That should be 0644 or 0755. Those are octal constants for them to make sense that way.

0644 means read/write (6) to owner; read only to group and world.

0755 means read/write/execute (7) to owner; read/execute to group and world.

Upvotes: 1

Sathish
Sathish

Reputation: 3870

When you need to apply file permission you need to use octal values! when you use integer values, its invalid

Try this-

int perm = 0644; // or use mode_t perm = 0644;

fd=fopen(file_name,"wb"); 
fchmod(fd,perm);

Upvotes: 0

Related Questions