open函数与close函数

1.open()函数

头文件:
#include <fcntl.h>//在centos6.0中只要此头文件就可以
#include <sys/types.h>
#incldue <sys/stat.h>
功能:打开和创建文件(建立一个文件描述符,其他的函数可以通过文 件描述符对指定文件进行读取与写入的操作。)

原型

int open(const char*pathname,int flags);
int open(const char*pathname,int flags,mode_t mode);
参数说明:
1.pathname
  要打开或创建的目标文件
2.flags
  打开文件时,可以传入多个参数选项,用下面的
  一个或者多个常量进行“或”运算,构成falgs
  参数:
  O_RDONLY:   只读打开
  O_WRONLY:   只写打开
  O_RDWR:     读,写打开
这三个常量,必须制定一个且只能指定一个
  O_CREAT:    若文件不存在,则创建它,需要使
              用mode选项。来指明新文件的访问权限
  O_APPEND:   追加写,如果文件已经有内容,这次打开文件所
              写的数据附加到文件的末尾而不覆盖原来的内容
              

ps:open函数具体使用那个,和具体应用场景相关,如目标文件存在,使用两个参数的open,如果目标文件不存在,需要open创建,则第三个参数表示创建文件的默认权限

返回值

成功:新打开的文件描述符
失败:-1
open返回的文件描述符一定是最小的而且没有被使用的

fopen与open的区别

以可写的方式fopen一个文件时,如果文件不存在则会自动创建,而open一个文件时必须明确O_CREAT才会创建文件,否则文件不存在就出错返回

2.close()函数

头文件:#include<unistd.h>
功能:关闭一个已经打开的文件

原型

int close(int fd)
参数说明:
 fd:是需要关闭的文件描述符

返回值

成功:返回0;
失败:返回-1,并设置errno

打开的文件描述符一定要记得关闭,否则资源会被大量的占用,导致内存不够

3.open打开存在的文件

示例1:

#include <stdio.h>
#include <string.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>

int main()
{
	int fd=open("myfile.txt",O_WRONLY);//需要准备myfile.txt文件
	if(fd<0)
	{
		perror("open");
		exit(1);
	}
	const char*msg="hello open\n";
	int count = 6;
	while(count--)
	{
		write(fd,msg,strlen(msg));
	}
	close(fd);
	return 0;
}

运行结果:
在这里插入图片描述
示例2:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <unistd.h>
int main()
{
	int fd=open("myfile.txt",O_RDWR);
	if(fd<0)
	{
		perror("open");
		exit(1);
	}
	const char*msg="hello  hahaha\n";
	int count= 10;
	while(count--)
	{
		write(fd,msg,strlen(msg));
	}
	char buf[1024]= {0};
	int num=10;
	while(num--)
	{
		read(fd,buf,strlen(msg));
	}
	close(fd);
	return 0;
}

运行结果:
在这里插入图片描述

3.open打开不存在的文件

示例1:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <fcntl.h>

int main()
{
	int fd=open("file.txt",O_WRONLY|O_CREAT,0644); //file文件不存在,所以在书写第二个参数时,记得把O_CREAT加上, //如果不加O_CREAT的话,程序就会报此文件不存在
	if(fd<0)
	{
		perror("open");
		exit(1);
	}
	const char*msg="hello file\n";
	int count=10;
	while(count--)
	{
		write(fd,msg,strlen(msg));
	}
	close(fd);
	return 0;
}

运行结果:
在这里插入图片描述
参考资料:
https://blog.csdn.net/dangzhangjing97/article/details/79631173

猜你喜欢

转载自blog.csdn.net/mayue_web/article/details/88673456
今日推荐