cfileread-writeseeklseek

How can I use lseek() to get to the midpoint of a file?


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.


Solution

  • 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);