一、文件IO的基本概念
(一)定义
文件IO也被称为系统IO,它是属于系统调用层面的,是操作系统提供的接口函数,因此没有缓冲机制。
(二)特点
1.没有缓冲机制,每次调用都会引起系统调用
2.围绕文件描述符进行操作,文件描述符是一个非负整数,才打开文件时创建,可以把文件描述符理解成一个编号,通过这个编号间接找到文件并对其进行操作。
3.文件IO默认打开三个文件描述符,0(标准输入)、1(标准输出)、2(标准错误)
4.文件IO可以操作任意类型文件b(块设备文件)、c(字符设备文件)、-(普通文件)、l(链接文件)、s(套接字文件)、p(管道文件),不包括目录。
(三)操作
1.打开文件:open
2.关闭文件
3.读写操作:read、write
4.定位操作:lseek
二、函数接口
以下操作是基于Ubuntu16.04.7操作系统
(一)open
1.首先查man手册,看函数的功能、参数、返回值、以及所需要的头文件
1)先看这个简单的函数
int open(const char *pathname, int flags);
参数:
const char *pathname:见名知意思,肯定是函数路径
int flags:是个标志,接着查手册
2)常用的几个flags:
①文件以追加的方式打开
②如果文件不存在就创建
当我们的标志中有O_CREAT这个标志时,就要写第三个参数,第三个参数是创建文件的模式,也就是权限。
③大致的意思是文件存在就清空内容,但是生不生效时不确定的,得看是什么文件
④当它和O_CREAT一起使用的时候,如果这个文件已存在,就会open失败
3)返回值
打开成功返回一个新的文件描述符,失败就返回-1,可以根据返回值判断是否创建成功。
2.代码测试
1)只有两个参数时
①文件不存在时
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#include <string.h>
int main(int argc, char const *argv[])
{
int fd;
//常量保护:通过使用 const 修饰符,我们可以保证字符串不会被程序意外修改。同时提高接口兼容性
const char * filepath = "newfile.txt";
fd = open(filepath, O_EXCL);
if(fd < 0)
{
fprintf(stderr, "Error opening file: %s\n", strerror(errno));
return 1;
}
else
{
printf("file creat success\n");
}
return 0;
}
执行结果:
②文件存在时
执行结果
2)三个参数时
fd = open(filepath, O_RDWR | O_CREAT | O_EXCL,0666);
①文件不存在时
②文件存在时
3)容错机制
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#include <string.h>
int main(int argc, char const *argv[])
{
int fd;
//常量保护:通过使用 const 修饰符,我们可以保证字符串不会被程序意外修改。同时提高接口兼容性
const char *filepath = "newfile.txt";
fd = open(filepath, O_RDWR);
if (fd < 0)
{
if (errno == ENOENT)
{
fd = open(filepath, O_RDWR | O_CREAT, 0664);
if(fd < 0)
printf("error creating file\n");
return 1;
}
else
{
perror("Error opening file\n");
return 1;
}
}
else
{
printf("file opened successfully\n");
}
return 0;
}
(二)close
close 只有一个参数,就是文件描述符
关闭成功返回0,关闭失败返回-1
(三)read/write
参数分别是文件描述符,存放读取数据的地址,数据的大小
参数分别是文件描述符,存放要写入数据的地址,数据的大小
(四)lseek
参数分别是文件描述符、偏移量、相对位置
相对位置有以下几种,分别是文件开头,当前位置、文件末尾
如果成功返回值为文件的偏移位置,失败则返回-1