I am having trouble to understand why lseek
function is useful.
Assuming I got a parameter like this given to me from the user:
off_t offset = 10;
And I wanted to read from the offset 100 bytes.
I can use pread
like this:
void * buf = malloc(100);
if (buf == NULL) { exit(1);}
int res = pread(file_id, buf, 100, offset);
On the other hand, I understand I can set the file with lseek
like this:
off_t seek = lseek(file_id, offset, SEEK_SET);
So I believe I achieve reading using pread
already. What did I miss regarding lseek
in what it can do to help me read the file?
A function may have to read/write from/to a given file handle at a location that is not known to it (say current position), so you need to uncouple seeking from reading (or writing) because the caller may have a need to set the location.
More generally, many I/Os are just sequential so seeking is not necessary, while pread
forces seeking.