libuv fs再次读取文件打印

时间:2017-11-29 15:12:38

标签: c libuv

最近我正在编写一些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");
}

我正在阅读此文件只有一行文字:&#34; hello1234567 \ n&#34;, 缓冲区大小为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-&gt;结果,第二个数字是context-&gt; read_open_req-&gt;结果。

其他代码与official tutorial

类似

感谢。

1 个答案:

答案 0 :(得分:0)

终于发现了我的愚蠢错误 r = uv_fs_read(uv_default_loop(), read_req, open_req->result, &context->iov, 1, 0, read_cb);
params offset应为-1而不是0以从prev offset读取。