int creat(const char *filename, mode_t mode);
#filename:要创建的文件名
#mode:创建模式:只能控制创建用户的写属性,其余用户都是不可写,所以一般是755
a) S_IRUSR:可读 ->1
b) S_IWUSR:可写 ->2
c) S_IXUSR:可执行 ->
d) S_IRWXU:可读写执行 ->7
#返回值:成功返回0,不成功返回-1
应用举例
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
void create_file(char *filename)
{
if(creat(filename,0755)<0)
{
printf("create file %s failed !\n",filename);
exit(1);
}
else
printf("create file %s successed !\n",filename);
}
int main(int argc,char *argv[])
{
int i;
/*参数检查,第一个参数是程序执行文件,第二个参数至第N个参数都是需要创建的文件名*/
if(argc<2){
perror("you have not input the filename!\n");
exit(1);
}
/*特别注意这是从1开始*/
for(i=1;i<argc;i++)create_file(argv[i]);
exit(0);
}
运行程序后,可以看到打印了这样的语句:
ivan@ivan-virtual-machine:~/123$ gcc file1.c -o file1
ivan@ivan-virtual-machine:~/123$ ./file1 hello1
create file hello1 successed !
通过运行命令ls -l可以看到当前目录的属性:
ivan@ivan-virtual-machine:~/123$ ls -l
总用量 56
-rwxrwxr-x 1 ivan ivan 7306 6月 25 14:55 a.out
-rwxrwxr-x 1 ivan ivan 7306 6月 25 14:58 file
-rwxr-xr-x 1 ivan ivan 7300 6月 25 17:49 file1
-rw-rw-r-- 1 ivan ivan 517 6月 25 17:49 file1.c
-rw-rw-r-- 1 ivan ivan 550 6月 25 14:58 file_create.c
-rwxrwxr-x 1 ivan ivan 7385 6月 25 15:47 file_open
-rw-rw-r-- 1 ivan ivan 524 6月 25 15:47 file_open.c
-rwxrwxr-x 1 ivan ivan 7159 6月 25 14:32 hello
-rwxr-xr-x 1 ivan ivan 0 6月 25 17:49 hello1
-rw-rw-r-- 1 ivan ivan 74 6月 25 14:30 hello.c