How can I (programmatically) give write permission on a file to a particular user in Linux? Like, for example, its owner? Everyone has read access to this file.
User, Group and Other. Linux divides the file permissions into read, write and execute denoted by r,w, and x. The permissions on a file can be changed by 'chmod' command which can be further divided into Absolute and Symbolic mode. The 'chown' command can change the ownership of a file/directory.
To change file and directory permissions, use the command chmod (change mode). The owner of a file can change the permissions for user ( u ), group ( g ), or others ( o ) by adding ( + ) or subtracting ( - ) the read, write, and execute permissions.
The syntax is simple: chmod PERMISSIONS FILE. You can set file permissions in two ways: using numbers and letters. With this method, each permission is assigned a number: r=4, w=2 and x=1. You use each set's total number to assing the permission.
In a shell or shell script simply use:
chmod u+w <filename>
This only modifies the write bit for the user, all other flags remain untouched.
If you want to do it in a C program, you need to use:
int chmod(const char *path, mode_t mode);
First query the existing mode via
int stat(const char *path, struct stat *buf);
... and just set the write bit by doing newMode = oldMode | S_IWUSR
. See man 2 chmod
and man 2 stat
for details.
The octal mode 644
will give the owner read and write permissions, and just read permissions for the rest of the group, as well as other users.
read = 4
write = 2
execute = 1
owner = read | write = 6
group = read = 4
other = read = 4
The basic syntax of the command to set the mode is
chmod 644 [file name]
In C, that would be
#include <sys/stat.h>
chmod("[file name]", 0644);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With