如何在Linux中为文件提供写入权限?

boo*_*oom 17 c linux

我如何(以编程方式)将文件的写权限授予Linux中的特定用户?比如,它的拥有者?每个人都有对此文件的读取权限.

Dar*_*ust 25

在shell或shell脚本中,只需使用:

chmod u+w <filename>
Run Code Online (Sandbox Code Playgroud)

这仅修改用户的写入位,所有其他标志保持不变.

如果要在C程序中执行此操作,则需要使用:

int chmod(const char *path, mode_t mode);
Run Code Online (Sandbox Code Playgroud)

首先通过查询现有模式

int stat(const char *path, struct stat *buf);
Run Code Online (Sandbox Code Playgroud)

...然后只需设置写入位newMode = oldMode | S_IWUSR.查看man 2 chmodman 2 stat了解详情.

  • @Delan Azabani:海报说:*"将文件的写入权限授予特定用户"*.你的代码会给每个人*写访问权限,这可能不是海报想要的.如果要保留组和其他的访问模式,则必须使用所需标志查询当前模式和OR. (3认同)

Del*_*ani 9

八进制模式644将为所有者提供读写权限,并且只读取组的其余部分以及其他用户的权限.

read     = 4
write    = 2
execute  = 1
owner    = read | write = 6
group    = read         = 4
other    = read         = 4
Run Code Online (Sandbox Code Playgroud)

设置模式的命令的基本语法是

chmod 644 [file name]
Run Code Online (Sandbox Code Playgroud)

在C中,那将是

#include <sys/stat.h>

chmod("[file name]", 0644);
Run Code Online (Sandbox Code Playgroud)