open( )
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
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_APPEND 如果文件存在,则追加
O_CREAT 如果文件不存在,则创建
O_EXCL 一般与O_CREAT一起使用,表示如果文
件存在则open函数调用失败
O_TRUNC 如果文件存在则清空
mode:如果flags参数指定为O_CREAT,则必须有这个参数
表示创建的文件的权限,例如0664
返回值:
成功:文件描述符
失败:-1
标准io 文件io
r O_RDONLY
r+ O_RDWR
w O_WRONLY | O_CREAT | O_TRUNC, 0664
w+ O_RDWR | O_CREAT | O_TRUNC, 0664
a O_WRONLY | O_CREAT | O_APPEND, 0664
a+ O_RDWR | O_CREAT | O_APPEND, 0664
close( )
#include <unistd.h>
int close(int fd);
功能:关闭一个文件描述符
参数:
fd:指定的文件描述符
返回值:
成功:0
失败:-1
read( )
#include <unistd.h>
ssize_t read(int fd, void *buf, size_t count);
功能:从文件中读取数据
参数:
fd:指定的文件描述符
buf:保存读取的数据
count:预计读取的字节数
返回值:
成功:实际读取的字节数
失败:-1
如果读取到文件末尾,则返回0
write( )
#include <unistd.h>
ssize_t write(int fd, const void *buf, size_t count);
功能:向文件写入数据
参数:
fd:指定的文件描述符
buf:要写的数据
count:要写的字节数
返回值:
成功:写入文件的字节数
失败:-1
使用read和write函数实现cp命令的功能
lseek( )
#include <sys/types.h>
#include <unistd.h>
off_t lseek(int fd, off_t offset, int whence);
功能:设置或者获取文件的偏移量
参数:
fd:指定的文件描述符
offset:设置的偏移量
whence:相对位置
SEEK_SET 文件起始位置
SEEK_CUR 当前文件位置
SEEK_END 文件末尾位置
返回值:
成功:当前文件的偏移量
失败:-1