0

So I have a textfile with 10 words with 5 characters each, and I want to get to the midpoint of that file without having to call read multiple times so I wanted to use lseek. As I understand, lseek only uses the SET, CUR, and END flags.

So If I have a textfile and all the words are only 5 words long...

I can use SEEK_SET to get the current word I'm at which would be 5

I can use SEEK_CUR to get to the next word location, so 10, then 15 and so on

I can use SEEK_END to get to 100.

My question is, if I want to get somewhere in between, say spot 76 or 24, or in my case 50, how can I do that? I tried doing using lseek with SEEK_SET / 2 and it doesn't work.

  • I assume you have a single space/delimiter between each (5 char) word, so that's 6 chars/word for all but the last. So, position is `ipos * 6` where `ipos` is the Nth word (origin 0) you want (e.g. 0, 1, 2, ..., 9). So, 10/5 --> 5 --> 5 * 6 --> 30. So, `lseek(fd,30,SEEK_SET);` Or, more generally, `lseek(fd,ipos * 6,SEEK_SET);` Obviously, if you do _not_ have a delimeter between words, the multiplier is 5 instead of 6. – Craig Estey Sep 12 '22 at 03:26

1 Answers1

1

You seem to be confused as to what these flags do. From the man page:

SYNOPSIS #include <sys/types.h> #include <unistd.h>

   off_t lseek(int fd, off_t offset, int whence);

DESCRIPTION The lseek() function repositions the offset of the open file associated with the file descriptor fd to the argument offset according to the directive whence as follows:

   SEEK_SET
          The offset is set to offset bytes.

   SEEK_CUR
          The offset is set to its current location plus offset bytes.

   SEEK_END
          The offset is set to the size of the file plus offset bytes.

So you would use SEEK_SET to go to a specific location in the file, SEEK_CUR to go to a location relative to the current location, and SEEK_END to go to a location relative to the end of the file.

In your case, if you have 10 words of 5 characters each for a total of 50 bytes and want to go to the middle, you want to use SEEK_SET with an offset of 25. For example:

lseek(fd, 25, SEEK_SET);
dbush
  • 205,898
  • 23
  • 218
  • 273
  • Can you show me an example of using SEEK_SET with an offset of 25? Or any offset / numer? I am not familiar with the syntax and whatever tests I run on it are not getting the results I want. – mistahwhite Sep 12 '22 at 03:46
  • @mistahwhite See my edit. – dbush Sep 12 '22 at 03:50
  • Thanks I was confusing myself by using a variable. Didn't fully grasp it's usage till your edit. Thanks again – mistahwhite Sep 12 '22 at 03:57