目录起始权限是从777,普通文件起始权限从666
为何我们创建一个目录或文件,默认权限是你所看到的样子?
因为凡是在umask中出现的权限,都不应该在最终权限中出现!
最终权限=起始权限&(~umask)
已知:umask为0002,我们默认它是002
对目录:
对文件:同理
故我们想修改目录或文件的起始权限,可以通过设置umask的值来实现
示例:
①使文件或目录默认权限为000
在函数中,为了确保函数设置的对应文件权限就是设置的权限,通常会将umask设为0,让umask无法再起作用:
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
int main()
{
umask(0);//防止掩码影响最终生成的文件权限,故设为0
int fd = open("log.txt",O_WRONLY|O_CREAT,0666);//既创建又写入,创建log.txt并默认权限为rw-rw-rw-
if(fd < 0)
{
perror("open");
return 1;
}
//open success
printf("open success,fd: %d\n",fd);
return 0;
}