使用Libuv异步读写文件
起因
一直以为Libuv只是封装的事件库,看了之后才发现有文件异步读写操作,使用还是很方便的.代码示例
static uv_loop_t* loop;
static uv_file fs_handle;
static char buf[1024] = { 0 };
void uv_fs_read_cb1(uv_fs_t* req)
{
printf("read size:%d\n", req->result);
buf[req->result] = 0;
printf("content:%s\n", buf);
uv_fs_req_cleanup(req);
uv_fs_close(loop, req, fs_handle, NULL);
}
void uv_fs_cb1(uv_fs_t* req)
{
fs_handle = req->result;
uv_fs_req_cleanup(req);
uv_buf_t uv_buffer = uv_buf_init(buf, 1024);
uv_fs_read(loop, req, fs_handle, &uv_buffer, 1, 0, uv_fs_read_cb1);
}
//文件异步读写
int main(int argc, char* argv[])
{
loop = uv_default_loop();
uv_fs_t* req;
uv_fs_open(loop, &req, "1.txt", 0, O_RDWR, uv_fs_cb1); //使用libuv打开一个文件
uv_run(loop, UV_RUN_DEFAULT);
//system("pause");
return 0;
}
秋风
2020-09-20