
前面的一篇文章中,我已经详细的介绍了Linux文件权限的一些知识,现在我再来讲讲Linux编程中文件权限的相关操作。
修改文件的权限
熟悉Linux命令的人大概都会知道修改文件的权限的常用命令是chmod
.同样,在C语言中有一个用法十分类似的函数chmod函数.它的主要功能是修改文件的权限,函数原型是int chmod(const char* path, mode_t mode)
;权限改变成功的话就返回0,失败则返回-1,错误原因存于errno.另外,改函数所需要的头文件是`#inchude<sys/types.h>和#include<sys/stat.h>.知道了这些之后,我们就来举几个例子说明一下这个函数的用法.
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdlib.h>
int main()
{
chmod("test.txt", S_IRUSR | S_IRGRP | S_IROTH);
system("ls -ld test.txt");
return 0;
}
在这个程序中,我们将文件test.txt的权限修改为所有者具有读权限(S_IRUSR),组具有读权限(S_IRGRP),其他用户具有读权限(S_IRGRP),程序执行结果,如下所示:
-r--r--r-- 1 bird bird 0 Apr 16 09:47 test.txt
其中,函数chmod的mode的参数说明如下:
mode参数 | 说明 |
---|---|
S_IRUSR | 所有者具有读取权限 |
S_IWUSR | 所有者具有写入权限 |
S_IXUSR | 所有者具有执行权限 |
S_IRGRP | 组具有读取权限 |
S_IWGRP | 组具有写入权限 |
S_IXGRP | 组具有执行权限 |
S_IROTH | 其他用户具有读取权限 |
S_IWOTH | 其他用户具有写入权限 |
S_IXOTH | 其他用户具有执行权限 |
另外,我们也用到了system函数,这个函数可以用来调用其他程序,在这个程序中我用它来执行shell命令.
设置权限掩码
在之前的那篇博文(说说Linux文件权限那些事儿 )中我提到了umask
,在C语言中同样有一个可以设置权限掩码的函数umask
函数.这个函数的原型是mode_t umask(mode_t mask)
,mask是一个4位八进制数,它需要的头文件和chmod
一样.另外要注意它返回的是原来系统中的umask值,而不是新的umask的值.下面我们还是举个例子说明它的用法.
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
int main()
{
mode_t n_umask, o_umask;
n_umask = 0666;
system("echo -n 'The previous umask is: '");
system("umask");
system("touch file1");
system("ls -l file1");
umask(n_umask); //set the new umask
printf("The current umask is %o\n", n_umask);
system("touch file2");
system("ls -l file2");
return 0;
}
在上面这个程序中,首先显示系统中原来的umask的值,然后创建文件,查看其权限信息,接着修改系统umask的值,创建文件查看权限信息.下面是程序执行结果:
The previous umask is: 0002
-rw-rw-r-- 1 bird bird 0 Apr 16 10:54 file1
The current umask is 666
---------- 1 bird bird 0 Apr 16 10:54 file2
对了,这个程序只有第一次执行才能看到正确的结果,因为第一次执行后产生的文件会对后面的执行产生影响.如果想要多次执行,可以执行前删除file1和file2,或者在程序中添加这条语句:
system("rm file*);
参考文献
- 金国庆, 刘家海等. Linux程序设计. 浙江大学出版社. 2015
- Neil Matthew, Richard Stones. 人民邮电出版社. 2010
网友评论