1

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?

Eyzuky
  • 1,843
  • 2
  • 22
  • 45
  • 3
    Neither lseek nor pread are part of Standard C++. Or of Standard C, for that matter. –  Jun 03 '17 at 14:35
  • My bad, what would you name it? C? Linux? – Eyzuky Jun 03 '17 at 14:36
  • It looks more like C code than C++. I've added a POSIX tag. –  Jun 03 '17 at 14:37
  • @NeilButterworth Why does that matter? – Galik Jun 03 '17 at 14:38
  • @NeilButterworth If its going through a `C++` compiler then it is `C++` code. – Galik Jun 03 '17 at 14:38
  • @Galik Because we don't want the C++ tag being swamped with questions specifically about the millions of non-standard APIs that are out there. –  Jun 03 '17 at 14:39
  • @NeilButterworth So why do we even have tags like `posix` and `lseek` and `mysql` etc...? – Galik Jun 03 '17 at 14:40
  • 2
    @Galik That question makes no sense. We have those tags for questions about posix and linux. I've already tagged this as posix. –  Jun 03 '17 at 14:41
  • @NeilButterworth there are 500K questions tagged "c++", I don't think you are going to be able to avoid "swamping" – M.M Jun 07 '17 at 05:09
  • The simple answer is that `lseek()` came first, by about 30 years. – user207421 Jun 07 '17 at 06:20

1 Answers1

1

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.

Jean-Baptiste Yunès
  • 34,548
  • 4
  • 48
  • 69