1、文件I/O又被称为低级磁盘I/O,它没有缓冲区,可以直接读写实际文件2、这样也存在一些坏处,频繁的系统调用会增加系统开销;
3、同时文件I/O使用文件描述符来打开文件,访问的文件类型更加丰富
头文件:
#include
#include
函数原型:
int open(const char *pathname,int flag,int perms);
例子:
int fd=open("text.c",O_RDONLY);
函数参数:
1、pathname 将要打开的文件
2、flags 文件打开方式
(1)O_RDONLY 只读方式打开
(2)O_WRONLY 只写方式打开
(3)O_RDWR 可读可写方式打开
(4)O_CREAT 如果文件不存在就新建
(5)O_TRUNC 如果文件存在就清空
3、perms 新建的文件的访问权限,只有 flags中包含O_CREAT 才有效
返回值:一个文件描述符
头文件:
#include
函数原型:
ssize_t close(int fd);
例子:
close(fd);
头文件:
#include
函数原型:
ssize_t read(int fd,void *buf,size_t count);
例子:
int fd=open("text.c",O_RDONLY);
char buf[100];
int ret=read(fd,buf,100);
函数参数:
1、fd 文件描述符
2、buf 读到的数据,存放的位置(以字节为单位读)
3、count 将要读取的数据的字节数
函数返回值:读到的字节数
头文件:
#include
函数原型:
ssize_t write(int fd,void *buf,size_t count);
例子:
int fd=open("text.c",O_RDWR|O_CREAT,0666)
char buf[]={"hello world!"};
int ret=write(fd,buf,sizeof(buf));
头文件:
#include
#include
函数原型:
off_t lseek(int fd,off_t offset,int whence);
例子:
int fd=open("text.c",O_RDONLY);
lseek(fd, -128, SEEK_END);//用法与fseek一致
头文件:
#include
#include
函数原型:
struct stat {
dev_t st_dev; //文件的设备编号
ino_t st_ino; //节点
mode_t st_mode; //文件的类型和存取的权限
nlink_t st_nlink; //连到该文件的硬连接数目,刚建立的文件值为1
uid_t st_uid; //用户ID
gid_t st_gid; //组ID
dev_t st_rdev; //(设备类型)若此文件为设备文件,则为其设备编号
off_t st_size; //文件字节数(文件大小)
unsigned long st_blksize; //块大小(文件系统的I/O 缓冲区大小)
unsigned long st_blocks; //块数
time_t st_atime; //最后一次访问时间
time_t st_mtime; //最后一次修改时间
time_t st_ctime; //最后一次改变时间(指属性)
};
int stat(const char *file_name,struct stat *buf);
头文件:
#include
#include
函数原型:
DIR *opendir(const char *name);
例子:
DIR *dp=opendir("text");
头文件:
#include
#include
函数原型:
struct dirent
{
ino_t d_ino; //d_ino 此目录进入点的inode
ff_t d_off; //d_off 目录文件开头至此目录进入点的位移
signed short int d_reclen; //d_reclen _name 的长度, 不包含NULL 字符
unsigned char d_type; //d_type d_name 所指的文件类型 d_name 文件名
char d_name[256];
};
struct dirent *readdir(DIR *dir);
文件IO和标准IO的区别
区别一:用途不同,标准I/O通常只访问普通文件,文件I/O可以读取目录文件,设备文件,管道文件等
区别二:是否有缓冲机制,标准IO有缓冲(全缓冲、行缓冲、不缓冲),文件IO无缓冲
区别三:函数来源不同。标准IO来自于标准C库,文件IO来自于Linux系统内核
区别四:这两种IO操作文件的入口不一样。标准IO操作的文件入口是文件流,文件IO操作的文件入口是文件描述符。