0
最近libuvを使ってファイルを読み込んで内容を出力するためのコードをいくつか書いています。
しかし、なぜ私のコードが最初のバッファを2回印刷するのかわかりません。libuv fsファイルをもう一度読み取る
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_open_req->結果read_req->結果です。
その他のコードがofficial tutorial
おかげに似ています。