前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >libuv 同时读写文件

libuv 同时读写文件

原创
作者头像
8菠萝
发布2022-11-14 16:27:45
7880
发布2022-11-14 16:27:45
举报
文章被收录于专栏:菠萝上市没有
代码语言:txt
复制
// 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 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档