Introduction
简单的文件系统读写是通过 uv_fs_*
函数 uv_fs_t
结构体实现的.
libuv FileSystem Operation
和 Socket Operation
操作不一样, socket 操作使用的是异步非阻塞的方法, 而FileSystem Operation
在内部使用的是阻塞的函数, 但是是通过异步的方法调用的
读写文件
获取文件描述符:
int uv_fs_open(uv_loop_t * loop, uv_fs_t * req, const char * path, int flags, int mode, uv_fs_cb cb)
读取文件:
int uv_fs_read(uv_loop_t* loop, uv_fs_t* req, uv_file file, const uv_buf_t bufs[], unsigned int nbufs, int64_t offset, uv_fs_cb cb)
其中
uv_file file
一般填写的是打开之后的文件描述符. 在调用cb
回调函数之前, 缓冲区会被自动填满. 如果 read 回调函数中req->result
为0,则代表遇到了EOF
写文件:
int uv_fs_write(uv_loop_t* loop, uv_fs_t* req, uv_file file, const uv_buf_t bufs[], unsigned int nbufs, int64_t offset, uv_fs_cb cb)
关闭文件:
int uv_fs_close(uv_loop_t * loop, uv_fs_t * req, uv_file file, uv_fs_cb cb)
回调函数函数签名:
void callback(uv_fs_t * req);
完整代码:
void on_read(uv_fs_t *req);
uv_fs_t open_req;
uv_fs_t read_req;
uv_fs_t write_req;
static char buffer[8];
static uv_buf_t iov;
void on_write(uv_fs_t *req) {
if (req->result < 0) {
fprintf(stderr, "Write error: %s\n", uv_strerror((int)req->result));
}
else {
fprintf(stdout, "[on_write] req->Result = %d\n", req->result);
uv_fs_read(uv_default_loop(), &read_req, open_req.result, &iov, 1, -1, on_read);
}
}
void on_read(uv_fs_t *req) {
if (req->result < 0) {
fprintf(stderr, "Read error: %s\n", uv_strerror(req->result));
}
else if (req->result == 0) {
fprintf(stdout, "[on_read] req->Result = %d\n", req->result);
uv_fs_t close_req;
// synchronous
uv_fs_close(uv_default_loop(), &close_req, open_req.result, NULL);
}
else if (req->result > 0) {
iov.len = req->result;
fprintf(stdout, "[on_read] req->Result = %d\n", req->result);
uv_fs_write(uv_default_loop(), &write_req, 1, &iov, 1, -1, on_write);
}
}