All about programming in GNU/LINUX

illustration of lseek system call in GNU/LINUX

 

The lseek( ) system call is provided to set the file position of a file descriptor to a given value.

#include <sys/types.h>

#include <unistd.h>

off_t lseek (int fd, off_t pos, int origin);

 

Description of the arguments to lseek

1.fd=file descriptor of the open file

 

2.pos=offset

 

3.The behavior of lseek( ) depends on the origin argument, which can be one of the following:

SEEK_CUR

The current file position of fd is set to its current value plus pos, which can be negative, zero, or positive. A pos of zero returns the current file position value

 

new file postion=current file position + offset(the pos argument to lseek)

 

SEEK_END

The current file position of fd is set to the current length of the file plus pos,

which can be negative, zero, or positive. A pos of zero sets the offset to the end

of the file.

 

new file postion= file position of End Of the File + offset

SEEK_SET

The current file position of fd is set to pos.the offset is measured from the beggining of the file. A pos of zero sets the offset to the beginning of the file.

 

new file postion= offset

The call returns the new file position on success. On error, it returns -1 and errno is set as

appropriate.

 

For example, to set the file position of fd to 1000:

off_t ret;

ret = lseek (fd, (off_t) 1000, SEEK_SET);

if (ret == (off_t) -1)

/* error */

 

 

Alternatively, to set the file position of fd to the end of the file:

off_t ret;

ret = lseek (fd, 0, SEEK_END);

if (ret == (off_t) -1)

/* error */

 

As lseek( ) returns the updated file position, it can be used to find the current file position

via a SEEK_CUR to zero:

int pos;

pos = lseek (fd, 0, SEEK_CUR);

if (pos == (off_t) -1)

/* error */

else

/* ‘pos’ is the current position of fd */

By far, the most common uses of lseek( ) are seeking to the beginning, seeking to the end,

or determining the current file position of a file descriptor.

 

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s