Home | History | Annotate | Line # | Download | only in uvcat
      1 #include <assert.h>
      2 #include <stdio.h>
      3 #include <fcntl.h>
      4 #include <uv.h>
      5 
      6 void on_read(uv_fs_t *req);
      7 
      8 uv_fs_t open_req;
      9 uv_fs_t read_req;
     10 uv_fs_t write_req;
     11 
     12 static char buffer[1024];
     13 
     14 static uv_buf_t iov;
     15 
     16 void on_write(uv_fs_t *req) {
     17     if (req->result < 0) {
     18         fprintf(stderr, "Write error: %s\n", uv_strerror((int)req->result));
     19     }
     20     else {
     21         uv_fs_read(uv_default_loop(), &read_req, open_req.result, &iov, 1, -1, on_read);
     22     }
     23 }
     24 
     25 void on_read(uv_fs_t *req) {
     26     if (req->result < 0) {
     27         fprintf(stderr, "Read error: %s\n", uv_strerror(req->result));
     28     }
     29     else if (req->result == 0) {
     30         uv_fs_t close_req;
     31         // synchronous
     32         uv_fs_close(uv_default_loop(), &close_req, open_req.result, NULL);
     33     }
     34     else if (req->result > 0) {
     35         iov.len = req->result;
     36         uv_fs_write(uv_default_loop(), &write_req, 1, &iov, 1, -1, on_write);
     37     }
     38 }
     39 
     40 void on_open(uv_fs_t *req) {
     41     // The request passed to the callback is the same as the one the call setup
     42     // function was passed.
     43     assert(req == &open_req);
     44     if (req->result >= 0) {
     45         iov = uv_buf_init(buffer, sizeof(buffer));
     46         uv_fs_read(uv_default_loop(), &read_req, req->result,
     47                    &iov, 1, -1, on_read);
     48     }
     49     else {
     50         fprintf(stderr, "error opening file: %s\n", uv_strerror((int)req->result));
     51     }
     52 }
     53 
     54 int main(int argc, char **argv) {
     55     uv_fs_open(uv_default_loop(), &open_req, argv[1], O_RDONLY, 0, on_open);
     56     uv_run(uv_default_loop(), UV_RUN_DEFAULT);
     57 
     58     uv_fs_req_cleanup(&open_req);
     59     uv_fs_req_cleanup(&read_req);
     60     uv_fs_req_cleanup(&write_req);
     61     return 0;
     62 }
     63