-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfs.c
101 lines (82 loc) · 2.18 KB
/
fs.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
#include <stdio.h>
#include <stdlib.h>
#include <uv.h>
void on_open(uv_fs_t *req);
void on_read(uv_fs_t *req);
void on_write(uv_fs_t *req);
uv_fs_t open_req;
uv_fs_t read_req;
uv_fs_t write_req;
uv_fs_t close_req;
uv_buf_t buffer;
void on_open(uv_fs_t *req) {
if (req->result != -1) {
int s = 0;
fprintf( stderr, "on_open: enq read request\n");
s = uv_fs_read(uv_default_loop(), &read_req, req->result,
&buffer, 1, -1, on_read);
if ( s < 0) {
fprintf( stderr, "failure on uv_fs_read\n");
}
}
else {
fprintf(stderr, "Error opening file!\n");
}
}
#define STDOUT 1
void on_read(uv_fs_t *req) {
uv_fs_req_cleanup(req);
if (req->result < 0) {
fprintf(stderr, "Read error!\n");
}
else if (req->result == 0) {
// done reading, enqueue close request
// uv_fs_t close_req;
fprintf( stderr, "on_read: enq close request\n");
uv_fs_close(uv_default_loop(), &close_req, open_req.result, NULL);
}
else {
int s = 0;
fprintf( stderr, "on_read: enq write request\n");
s = uv_fs_write(uv_default_loop(), &write_req, STDOUT,
&buffer, 1, -1, on_write);
if ( s < 0) {
fprintf( stderr, "failure on uv_fs_write\n");
}
}
}
void on_write(uv_fs_t *req) {
uv_fs_req_cleanup(req);
if (req->result < 0) {
fprintf(stderr, "Write error!");
}
else {
int s = 0;
fprintf( stderr, "on_write: enq read request\n");
s = uv_fs_read(uv_default_loop(), &read_req, open_req.result,
&buffer, 1, -1, on_read);
if ( s < 0) {
fprintf( stderr, "failure on uv_fs_read\n");
}
}
}
int main(int argc, char **argv) {
unsigned int len = 1000*sizeof(char);
char *base = (char *)malloc(len);
int s = 0;
buffer = uv_buf_init(base, len);
s = uv_fs_open(uv_default_loop(), &open_req, argv[1], O_RDONLY, 0, on_open);
if ( s < 0) {
fprintf( stderr, "failure on uv_fs_open\n");
}
s = uv_run(uv_default_loop(), UV_RUN_DEFAULT);
if ( s < 0) {
fprintf( stderr, "failure on uv_run\n");
}
free(buffer.base); buffer.base=NULL;
uv_fs_req_cleanup(&open_req);
uv_fs_req_cleanup(&read_req);
uv_fs_req_cleanup(&write_req);
uv_fs_req_cleanup(&close_req);
return 0;
}