help
help copied to clipboard
Reading a file synchronously
Hello All,
I'm trying to read a file synchronously, uv_fs_read returns EFAULT. Is there something wrong with my code?
`uv_fs_t open_req; uv_fs_t close_req; uv_fs_t read_req; int ret = 0; uv_buf_t buffer; unsigned int len = 1000*sizeof(char);
char *base = (char *)malloc(len); buffer = uv_buf_init(base, len);
ret = uv_fs_open(NULL, &open_req, "/tmp/test.txt", O_RDWR, 0644, NULL);
if(ret < 0) { fprintf(stderr, "error opening file: %s\n", uv_strerror((int)open_req.result)); return(false); }
ret = uv_fs_read(NULL, &read_req, open_req.result, buffer.base, buffer.len, 0, NULL);
if(ret < 0) { fprintf(stderr, "error reading file: %s-%s\n", uv_err_name(ret), uv_strerror((int)read_req.result)); return(false); }
uv_fs_close(NULL, &close_req, open_req.result, NULL);
free(buffer.base);`
Thanks, -G
Have you tried it with a non-NULL uv_loop_t?
Yes. I have tried with a loop. It doesn't seem to make any difference.There are actually several places in the library source that do this. Unfortunately, I haven't had time to decipher the whole INIT/POST thing yet.
uv_fs_read --> preadv --> errors as from read and lseek.
EFAULT is listed as an error for read:
EFAULT
buf is outside your accessible address space.
The signature for uv_fs_read is:
int uv_fs_read(uv_loop_t* loop, uv_fs_t* req, uv_file file, const uv_buf_t bufs[], unsigned int nbufs, int64_t offset, uv_fs_cb cb)
You are calling it as:
ret = uv_fs_read(NULL, &read_req, open_req.result, buffer.base, buffer.len, 0, NULL);
I haven't tried your code, but it looks like instead of bufs, nbufs (4th and 5th args) you are providing the address of your buffer base and the length of that buffer.
Do you think something like this is what you should be providing?
ret = uv_fs_read(NULL, &read_req, open_req.result, &buffer, 1, 0, NULL);
That's the ticket!
Thanks, -G