main.c 1.6 KB

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