【问题标题】:libuv fs read file print one more timelibuv fs 读取文件再打印一次
【发布时间】:2017-11-29 15:12:37
【问题描述】:

最近我正在编写一些 c 代码来简单地读取文件并使用 libuv 打印出内容。
但我不知道为什么我的代码会打印两次第一个缓冲区。

void open_cb(uv_fs_t* open_req){
    int r = 0;
    if(open_req -> result < 0 ) printf("open_req");

    context_t* context = open_req -> data;

    size_t buf_len = sizeof(char) * BUF_SIZE;
    char *buf = malloc(buf_len);
    context->iov = uv_buf_init(buf, buf_len);
    context->times = 0;

    uv_fs_t *read_req = malloc(sizeof(uv_fs_t));
    context->read_req = read_req;
    read_req->data = context;
    r = uv_fs_read(uv_default_loop(), read_req, open_req->result, &context->iov, 1, 0, read_cb);    
}
void read_cb(uv_fs_t* read_req){
    int r = 0;

    //uv_fs_t* close_req = mollac(sizeof(uv_fs_t));
    if(read_req->result < 0){
        printf("read_req");
        return;
    }else if(read_req->result == 0){
        printf("read finish\n");
        return;
    }

    context_t* context = read_req->data;

    printf("%zu %zu", read_req->result, context->read_open_req->result);
    printf("%i :", context->times);
    printf("%s\n", context->iov.base);

    size_t buf_len = sizeof(char) * BUF_SIZE;
    char *buf = malloc(buf_len);
    context->iov = uv_buf_init(buf, buf_len);
    context->times++;
    read_req->data = context;

    r = uv_fs_read(uv_default_loop(), read_req, context->read_open_req->result, &context->iov, 1, -1, read_cb);
    if(r<0) printf("read_req");
}

我正在阅读这个文件,其中只有一行文本:“hello1234567\n”, 缓冲区大小为 5,因此每次打印 5 个字符。
然而结果是

read result:5, open result:10
time: 0 :hello
read result:5, open result:10
time: 1 :hello
read result:5, open result:10
time: 2 :12345
read result:3, open result:10
time: 3 :67

read finish

第一个数字是 read_req->result,第二个数字是 context->read_open_req->result。

其他代码与official tutorial类似

谢谢。

【问题讨论】:

    标签: c libuv


    【解决方案1】:

    终于发现了我的愚蠢错误。
    r = uv_fs_read(uv_default_loop(), read_req, open_req-&gt;result, &amp;context-&gt;iov, 1, 0, read_cb);
    参数偏移量应该是 -1 而不是 0 从 prev 偏移量读取。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-03-02
      • 1970-01-01
      • 2023-03-08
      • 2022-07-11
      • 1970-01-01
      • 1970-01-01
      • 2020-06-12
      • 2022-07-11
      相关资源
      最近更新 更多