0

With chmod I can assign permissions like

chmod(file, S_IRUSR);

Is there a way to only take away the read permission from the user?

I've tried

chmod(file, !S_IRUSR);

and chmod(file, -S_IRUSR);

Neither work.

Jonathon Reinhart
  • 132,704
  • 33
  • 254
  • 328
user3436529
  • 27
  • 1
  • 5

1 Answers1

1

You can't change individual permission bits using chmod(2) like you can with the command-line utility. You can only set a new complete set of permissions.

To implement a change, you need to read them first, with stat(2), toggle the desired bits from the st_mode field, and then set them with chmod(2).

The following code will remove clear the S_IRUSR bit for test.txt, and set the S_IXUSR bit. (For brevity, error checking has been omitted.)

#include <sys/stat.h>

int main(void)
{
    struct stat st;
    mode_t mode;
    const char *path = "test.txt";

    stat(path, &st);

    mode = st.st_mode & 07777;

    // modify mode
    mode &= ~(S_IRUSR);    /* Clear this bit */
    mode |= S_IXUSR;       /* Set this bit   */

    chmod(path, mode);

    return 0;
}
Jonathon Reinhart
  • 132,704
  • 33
  • 254
  • 328
  • @user3436529 It is the [bitwise OR assignment operator](http://en.wikipedia.org/wiki/Bitwise_operations_in_C#Bitwise_assignment_operators). `a |= 1` is the same as `a = a | 1`. It means any bits that are 1 in the left-hand side, OR the right-hand side will be 1 when they are assigned to the left-hand side. You may also want to read [this question](http://stackoverflow.com/q/47981/119527). – Jonathon Reinhart Mar 16 '15 at 03:19