Bootstrap

Linux系统调用接口---使用open函数创建/截断文件

Linux系统调用接口—使用open函数创建/截断文件

1 open函数讲解

  open函数不仅可以打开一个文件,还可以创建一个文件或者去截断一个文件。本文将介绍如何使用open函数去创建一个文件或者去截断一个文件。

1.1 使用man命令查看open函数

man 2 open

在这里插入图片描述
  在open函数描述中我们可以看到函数需要包含的头文件、函数原型、返回值以及参数说明等。

  • 需要包含的头文件
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
  • 函数原型
int open(const char *pathname, intflags);   /*比较常用*/
int open(const char *pathname, intflags, mode_tmode);
  • 返回值

    1. 成功,返回句柄,我们后续对文件的读写、关闭等都是通过句柄来操作的。
    2. 失败,返回-1。
  • 参数说明

    1. pathname:文件路径名,或者文件名。
    2. flags:表示打开文件所采用的操作。常用选项是:O_RDONLY(只读);O_WRONLY(只写); O_RDWR(可读写);O_CREAT(文件不存在时,创建该文件);O_TRUNC(文件存在,将其长度截断为0);
    3. mode:当flags选项是O_CREAT时,需要使用mode指定文件权限。

1.2 实验测试

代码示例:

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <unistd.h>

/*
 * ./create 1.txt
 * argc = 2
 * argv[0] = "./create"
 * argv[1] = "1.txt"
*/

int main(int argc,char** argv)
{
	int fd;
	
	if(argc != 2)
	{
		printf("Usage: %s <file>\n",argv[0]);
		return -1;
	}

	fd = open(argv[1],O_RDWR | O_CREAT | O_TRUNC);
	if(fd < 0)
	{
		printf("can not open file %s\n",argv[1]);
		printf("errno :%d\n",errno);
		printf("err :%s\n",strerror(errno));
		perror("open");
	}
	else 
	{
		printf("fd = %d\n",fd);
	}

	while(1)
	{
		sleep(10);
	}
	close(fd);
	
	return 0;
}
  1. 将上述代码编译
gcc -o create ./create.c
  1. 运行程序(打开的文件不存在)
./create 1.txt

在这里插入图片描述
当我们打开一不存在的文件,它会自动帮我们创建一个文件,权限随机。

  1. 运行程序(打开的文件存在,并且里面含有内容)
echo hello > 1.txt
./create 1.txt

在这里插入图片描述
当我们打开的文件已经存在了,我们会将该文件截断,其文件的权限和之前存在的文件权限保持一致。

  1. 创建一个文件,并指定其权限
    我们需要将我们的代码的mode参数加上,我们将权限设置为0777。
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <unistd.h>

/*
 * ./create 1.txt
 * argc = 2
 * argv[0] = "./create"
 * argv[1] = "1.txt"
*/

int main(int argc,char** argv)
{
	int fd;
	
	if(argc != 2)
	{
		printf("Usage: %s <file>\n",argv[0]);
		return -1;
	}

	fd = open(argv[1],O_RDWR | O_CREAT | O_TRUNC,0777);
	if(fd < 0)
	{
		printf("can not open file %s\n",argv[1]);
		printf("errno :%d\n",errno);
		printf("err :%s\n",strerror(errno));
		perror("open");
	}
	else 
	{
		printf("fd = %d\n",fd);
	}

	while(1)
	{
		sleep(10);
	}
	close(fd);
	
	return 0;
}

在这里插入图片描述
我们利用mode设置了权限信息,但是为什么我们最后生成的1.txt文件的权限有点不一样呢?这将引出我们接下来介绍的umask,umask与mode参数结合才会生成我们最终的文件权限。

2 umask命令

  • 查看umask值
umask

在这里插入图片描述

  • umask与mode结合生成文件权限
    在这里插入图片描述
      使用umask命令看到我们禁用的文件权限,我们将~umask&mode结合便是最终的文件权限, ~0002&0777 = 0775,0775便是我们上述文件的权限。
;