lseek()
PROTOTYPE
#include <posix.h>
off_t lseek(int fid, off_t offset, int whence);
DESCRIPTION
lseek() sets the current position of the open regular file specified by fid. The new position is offset number of bytes from the position determined by whence, which is one of the following:
- SEEK_SET - the new position is offset bytes from the beginning of the file
- SEEK_CUR - the new position is its current value plus offset bytes
- SEEK_END - the new position is set to the file size plus offset bytes
offset is signed and may specify a backward or a forward seek, but it is illegal to seek back before a file’s beginning. lseek() may move the position forward past the end of existing data. If a write is performed while the file’s position is past its end, the file is expanded and the gap between the current position and the previous end is filled with zeros.
If successful, lseek() clears the file’s end-of-file indicator, drops any byte stored on its file control block by ungetc(), and returns the new file position. Otherwise, it sets errno and returns -1.
ERROR CODES
| EBADF | fid is not the descriptor of an open file. |
| EINVAL | whence is invalid or the new position would be before the file’s start. |
| EISDIR | The specified file is a directory. |
EXAMPLE
/*-----------------------------------------------------------------*/
/* Implement binary search algorithm. */
/*-----------------------------------------------------------------*/
low = 0; high = NumRecords - 1;
for (;;)
{
/*---------------------------------------------------------------*/
/* Seek to half-way point. */
/*---------------------------------------------------------------*/
pos = (low + high) / 2;
if (lseek(fid, pos * sizeof(Record), SEEK_SET) == (off_t)-1)
error("lseek() failed");
++num_seeks;
/*---------------------------------------------------------------*/
/* Read record at requested offset. */
/*---------------------------------------------------------------*/
rc = read(fid, &record, sizeof(Record));
if (rc != sizeof(Record))
error("read() failed");
/*---------------------------------------------------------------*/
/* Update high or low pointer or break, depending on comparison. */
/*---------------------------------------------------------------*/
if (ssn < record.ssn)
high = pos - 1;
else if (ssn > record.ssn)
low = pos + 1;
else
break;
if (low > high)
break;
}