linux中的文件的权限修改可通过chmod命令来修改,也可以通过编程来实现文件权限的修改,我们可以通过man 2 chmod查看这个函数是如何使用的。
如下是一个修改两个文件的权限的demo:
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
#include <stdio.h>
int main(int argc,char *argv[])
{
int fd, ret;
if(argc < 3)//判断参数个数
{
printf("\nplease input the file path!\n");
return 1;
}
//chmod test
ret = chmod(argv[1], 0777);
if(ret)
{
printf("\nplease make sure the file path!\n");
return 1;
}
//fchmod test
fd = open(argv[2], O_RDWR|O_NOCTTY|O_NDELAY);
if(fd < 0)
{
printf("please make sure file path!\n");
return 1;
}
ret = fchmod(fd, 0777);
if(ret)
{
printf("\nplease make sure the file path!\n");
return 1;
}
return 0;
}
我们把编写好的deno放入ubuntu中,然后使用编译命令gcc chmod.c -o chmod生成chmod可执行文件:
我们在同一个文件夹下建立两个文件test1与test2:
通过ls -l可以看到这两个文件的权限为rw-r--r--,也即是644,我们运行可执行文件: ./chmod test1 test2,卡一看到权限改变了,变成了777: