文件I/O与标准I/O的比较:
标准IO:带缓存,大部分函数是在系统调用之上实现,操作对象 "流"
文件IO:不带缓存,直接和系统调用关联,操作对象"文件描述符"
一、打开文件
int open(const char *pathname, int flags);
int open(const char *pathname, int flags, mode_t mode);
功能:打开或创建文件
参数:
@pathname
文件所在路径
@flags
打开的方式
O_RDONLY(只读)
O_WRONLY(只写)
O_RDWR(读写)
O_TRUNC(清空)
O_APPEND(追加)
O_CREAT(不存在,则创建)
注意:这些方式可以通过"|"进行组合使用
@mode
指定新建文件的权限,如果有O_CREAT,必须指定这个参数
返回值:成功返回文件描述符,失败返回-1
fopen(pathname,"r")
-> open(pathname,O_RDONLY);
fopen(pathname,"r+") -> open(pathname,O_RDWR);
fopen(pathname,"w"); -> open(pathname,O_WRONLY | O_CREAT | O_TRUNC,0666);
fopen(pathname,"w+");-> open(pathname,O_RDWR | O_CREAT | O_TRUNC,0666);
fopen(pathname,"a"); -> open(pathname,O_WRONLY | O_CREAT | O_APPEND,0666);
fopen(pathname,"a+");-> open(pathname,O_RDWR | O_CREAT | O_APPEND,0666);
注意:
1.open获得文件描述符规则:最小未使用
2.open只能用来创建普通文件,不能创建设备文件(/dev/目录下的文件),但是可以打开设备文件
3.open函数创建的文件实际权限:mode & ~uamsk
二.读写
A.读文件
buf的定义//char buf[1024];
int read(int fd,void *buf,int count);
功能:从文件中读取数据
参数:
@fd
文件
@buf
读取数据存放的地址
@count
期望读取的字节数
返回值:成功返回实际读取的字节数,如果读到文件尾部返回0,失败返回 -1
B.写文件
int write(int fd,void *buf,int count);
功能:向文件中写数据
参数:
@fd
文件
@buf
写入数据存放的地址
@count
期望写入的字节数
返回值:成功返回实际写入的字节数,失败返回 -1
三.文件定位
off_t lseek(int fd, off_t offset, int whence);
功能:修改内核中的offset值
参数:
@fd
文件
@offset 偏移值 ,offset > 0向后偏移,offset < 0 向前偏移
@whence :SEEK_SET,SEEK_CUR,SEEK_END
返回值:成功返回新文件偏移(即更改后的偏移),失败返回(-1)
四.关闭文件
close(int fd)