Use of lseek()

lseek() :
lseek() system call is used for re-positioning the read-write pointer within a file. Suppose you have a file "F1" whose contents are:
               1234567890abcdefghij
when the file is opened for the first time the pointer within the file is always positioned at the top left corner i.e. the 1st character in the file. Reading and writing will always start at this point. Now if you read five characters the pointer will be positioned at '6'. Any command for reading or writing will start from this new location. To better understand run the code below:

#include 
#include 
#include
int main()
{
    int n,off;
    char buffer[10];
    n=open("F1",O_RDWR);
    read(n,buffer,5); //reads - 12345
    write(1,buffer,5);
    read(n,buffer,5); //reads - 67890
    write(1,buffer,5);
}

What if you wanted to read 'abcde' and not '67890' ?
This means we need to move the pointer within the file. lseek() helps us to reposition the pointer within the file.
Syntax for lseek() is:
off_t lseek(int fildes, off_t offset, int whence);
The 1st parameter is the file descriptor of the file in which you want to reposition the pointer. The 2nd parameter is the offset i.e. location where you want to position it and the 3rd parameter us the reference point for the offset i.e. from where you want to start counting the offset - beginning of the file(SEEK_SET) or from the current position of the pointer(SEEK_CUR) or from the end of the file (SEEK_END). If the call to lseek() is successful then it returns the position of the pointer within the file.

The 3 programs below demonstrate the use of lseek() with SEEK_SET, SEEK_CUR and SEEK_END.

Program1:
#include 
#include 
#include

int main()
{
    int n,off;
    char buffer[10];
    n=open("F1",O_RDWR);
    read(n,buffer,5); //reads first 5 characters
    write(1,buffer,5);
    off=lseek(n,10,SEEK_SET); //pointer will be at 10th location from the beginning
    printf("\nCurrent position is %d\n",off); // to print the position of the pointer
    read(n,buffer,5);
    write(1,buffer,5);
}
Output:  
12345
Current position is 10 
abcde

Note: the first character in the file is referred as 0th position

Program 2:
#include 
#include 
#include

int main()
{
    int n,off;
    char buffer[10];
    n=open("F1",O_RDWR);
    read(n,buffer,5); //reads first 5 characters
    write(1,buffer,5);
    off=lseek(n,10,SEEK_CUR); //pointer is moved 10 position ahead from current position
    read(n,buffer,5);
    write(1,buffer,5);
}

Output:
12345fghij

Program3:
#include 
#include 
#include

int main()
{
    int n,off;
    char buffer[10];
    n=open("F1",O_RDWR);
    read(n,buffer,5); //reads first 5 characters
    write(1,buffer,5);
    off=lseek(n,-3,SEEK_END); //pointer is placed at 3rd position from the END
    printf("\nCurrent position is %d\n",off); //Note the value for 'off' carefully
    read(n,buffer,3);
    write(1,buffer,3);
}
 Output:
12345
Current position is 18
ij