user3436529
user3436529

Reputation: 27

Removing permissions on a file? C Programming

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.

Upvotes: 0

Views: 3337

Answers (1)

Jonathon Reinhart
Jonathon Reinhart

Reputation: 137398

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;
}

Upvotes: 1

Related Questions