creat函数
头文件:#include<sys/tpyes.h> #include <sys/stat.h> #include <fcntl.h>
格式: creat(const char *filename,mode_t);
含义:新建一个filename文件,文件权限为mode_t (0666 )
S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH
于是我们有如下代码 :
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
int main()
{
creat("pe.c",0666);
return 0;
}
ll pe.c
-rw-r--r-- 1 root root 0 2015-xx-26 14:36 pe.c
为什么呢 ?我们明明设置权限是0666啊
因为这里涉及到一个umask函数。当新文件被创建时,其最初的权限由文件创建掩码决定。
用户每次注册进入系统时,umask命令都被执行,并自动设置掩码改变默认值,新的权限将会把旧的覆盖。
就像这样:
0666 & ~022 = 0644
umark 函数
头文件:#include<sys/tpyes.h> #include <stat.h>
格式:umark(mode_t mask);
含义:设置默认文件的权限
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
int main()
{
umask(0);
if(creat("pc",0666)<0)
{
printf("creat error!\n");
exit(1);
}
umask(022);
if(creat("hei",0666) < 0)
{
printf("creat error hei!\n");
exit(1);
}
}
结果:
ll hei
-rw-r--r-- 1 root root 0 2015-11-26 14:44 hei
ll pc
-rw-rw-rw- 1 root root 0 2015-11-26 14:44 pc