// libuv实现边写边读
#include <stdio.h>
#include <spdlog/spdlog.h>
#include <uv.h>
typedef struct {
char buffer[1024];
uv_buf_t buf;
uv_fs_t open_read_fs;
uv_fs_t open_write_fs;
uv_fs_t read_fs;
uv_fs_t write_fs;
size_t offset = 0;
} read2write_t;
void on_write_cb(uv_fs_t* req);
void on_read_cb(uv_fs_t* req){
spdlog::info("read:{}", req->result);
auto data = (read2write_t *)req->data;
uv_fs_req_cleanup(req);
if (req->result < 0){
spdlog::error("read error");
}
else if (req->result == 0){
uv_fs_close(uv_default_loop(), &data->open_read_fs, data->open_read_fs.result, nullptr);
uv_fs_close(uv_default_loop(), &data->open_write_fs, data->open_write_fs.result, nullptr);
}
else{
data->write_fs.data = data;
data->buf = uv_buf_init(data->buffer, req->result);
int offset = data->offset;
data->offset += req->result;
uv_fs_write(uv_default_loop(), &data->write_fs, data->open_write_fs.result, &data->buf, 1, offset, on_write_cb);
}
}
void on_write_cb(uv_fs_t* req){
auto data = (read2write_t *)req->data;
uv_fs_req_cleanup(req);
if (req->result < 0){
spdlog::error("write error");
}
else{
data->read_fs.data = data;
uv_fs_read(uv_default_loop(), &data->read_fs, data->open_read_fs.result, &data->buf, 1, data->offset, on_read_cb);
}
}
void on_open_write_cb(uv_fs_t* req){
if (req->result < 0){
spdlog::error("write open file error:{}", uv_strerror(req->result));
}else {
auto data = (read2write_t*) req->data;
data->buf = uv_buf_init(data->buffer, sizeof(data->buffer));
data->read_fs.data = data;
uv_fs_read(uv_default_loop(), &data->read_fs, data->open_read_fs.result, &data->buf, 1, 0, on_read_cb);
}
}
void on_open_read_cb(uv_fs_t* req){
if (req->result < 0){
spdlog::error("read open file error:{}", uv_strerror(req->result));
}else{
auto data = (read2write_t*) req->data;
data->open_write_fs.data = data;
uv_fs_open(uv_default_loop(), &data->open_write_fs, "./test_write.txt", O_CREAT | O_WRONLY, 0, on_open_write_cb);
}
}
int main(){
read2write_t context;
context.open_read_fs.data = (void*)&context;
uv_fs_open(uv_default_loop(), &context.open_read_fs, "./test.txt", O_RDONLY, 0, on_open_read_cb);
return uv_run(uv_default_loop(), UV_RUN_DEFAULT);
}
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。