Pages

Thursday, June 16, 2011

lseek() - (C System Call)

lseek is a system call that is used to change the location of the read/write pointer of a file descriptor. The location can be set either in absolute or relative terms.

Required Include Files

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

Function Definition

off_t lseek(int fildes, off_t offset, int whence);
FieldDescription
int fildesThe file descriptor of the pointer that is going to be moved.
off_t offsetThe offset of the pointer (measured in bytes).
int whenceThe method in which the offset is to be interpreted (relative, absolute, etc.). Legal values for this variable are provided at the end.
return valueReturns the offset of the pointer (in bytes) from the beginning of the file. If the return value is -1, then there was an error moving the pointer.

Code Snippet

The following is an example using the lseek system call.
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
 
int main()
{
        int file=0;
        if((file=open("testfile.txt",O_RDONLY)) < -1)
                return 1;
 
        char buffer[19];
        if(read(file,buffer,19) != 19)  return 1;
        printf("%s\n",buffer);
 
        if(lseek(file,10,SEEK_SET) < 0) return 1;
 
        if(read(file,buffer,19) != 19)  return 1;
        printf("%s\n",buffer);
 
        return 0;
}
The output of the preceding code is:
$ cat testfile.txt 
This is a test file that will be used
to demonstrate the use of lseek.
$ ./testing 
This is a test file 
test file that will

Available Values for whence

ValueMeaning
SEEK_SETOffset is to be measured in absolute terms.
SEEK_CUROffset is to be measured relative to the current location of the pointer.
SEEK_ENDOffset is to be measured relative to the end of the file.

1 comment: