libuv学习(二) : FileSystem

这篇博客详细介绍了libuv库在文件系统操作中的应用,包括同步和异步的读写文件,文件系统操作如打开和关闭文件,以及如何监听文件变化。libuv使用缓冲区和流进行数据传输,并且提到了libuv接口设计的一些讨论,指出了其可能存在的不足。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Introduction

简单的文件系统读写是通过 uv_fs_* 函数 uv_fs_t 结构体实现的.

libuv FileSystem OperationSocket 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);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值