write系统调用
把buf的前nbytes字节写出至文件fildes.
原型
#include <unistd.h>
size_t write(int fildes, const void *buf, size_t nbytes);
返回值
返回实际写出的字节数,出错时返回-1并设置errno.
read系统调用
从文件fildes读入nbytes字节的数据,并放入buf.
原型
#include <unistd.h>
size_t read(int fildes, void *buf, size_t nbytes);
返回值
返回实际读入的字节数,出错时返回-1并设置errno.
open系统调用
原型
#include<fcntl.h> //支持posix规范则只需包含该头文件
#include<sys/types.h> //(其他unix系统)可能需要
#include<sys/stat.h> //可能需要
int open(const char *path, int oflags);
int open(const char *path, int oflags, mode_t mode);
参数
- path: 设备或文件名
- oflags
oflags是必选模式与可选模式的的按位或组合。
必选模式(只能指定一个)
模式 | 说明 |
---|---|
O_RDONLY | 只读(read only) |
O_WRONLY | 只写(write only) |
O_RDWR | 读写(read and write) |
可选模式 (指定一个或多个,或者不指定)
模式 | 说明 |
---|---|
O_CREAT | 创建文件,此模式下须指定mode参数 |
O_EXCL | 与O_CREAT一起使用 |
O_APPEND | 追加到文件尾端 |
O_TRUNC | 将文件长度截断为0 |
O_DIRECTORY | 如果path不是目录,则出错 |
- mode
O_CREAT模式下须指定mode参数:
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-VtZ5FyjN-1644655825989)(C:\Users\14595\AppData\Roaming\Typora\typora-user-images\image-20220210211419898.png)]
close系统调用
# include<unistd.h>
int close(int fd);
返回值
成功时返回0;失败时返回-1.
当一个进程终止时,内核自动关闭它所有的打开文件。
lseek系统调用
设置当前文件偏移量。参数和返回值与库函数fseek()相同。
原型
#include<unistd.h>
#include<sys/types.h>
off_t lseek(int fildes, off_t offset, int whence);
参数
参数名 | 说明 |
---|---|
stream | 指向文件 |
offset | 用来指定位置 |
whence | 定义offset的用法 |
- whence参数
whence取值 | 说明 |
---|---|
SEEK_SET | offset是一个绝对位置 |
SEEK_CUR | 基于当前(current)位置的相对位置 |
SEEK_END | 基于文件尾(end)的相对位置 |
返回值
成功时返回0;
失败时返回-1,并设置errno.
(off_t是整数类型,定义于sys/types.h中)