Positions a file to an arbitrary byte position and returns the new position. Format #include <unistd.h> off_t lseek (int file_desc, off_t offset, int direction);
1 – Arguments
file_desc An integer returned by open, creat, dup, or dup2. offset The offset, specified in bytes. The off_t data type is either a 32-bit or a 64-bit integer. The 64-bit interface allows for file sizes greater than 2 GB, and can be selected at compile time by defining the _LARGEFILE feature-test macro as follows: CC/DEFINE=_LARGEFILE direction An integer indicating whether the offset is to be measured forward from the beginning of the file (direction=SEEK_SET), forward from the current position (direction=SEEK_CUR), or backward from the end of the file (direction=SEEK_END).
2 – Description
The lseek function can position a fixed-length record-access file with no carriage control or a stream-access file on any byte offset, but can position all other files only on record boundaries. The available Standard I/O functions position a record file at its first byte, at the end-of-file, or on a record boundary. Therefore, the arguments given to lseek must specify either the beginning or end of the file, a 0 offset from the current position (an arbitrary record boundary), or the position returned by a previous, valid lseek call. This function returns the new file position as an integer of type off_t which, like the offset argument, is either a 64-bit integer if _LARGEFILE is defined, or a 32-bit integer if not. For a portable way to position an arbitrary byte location with any type of file, see the fgetpos and fsetpos functions. CAUTION If, while accessing a stream file, you seek beyond the end-of-file and then write to the file, the lseek function creates a hole by filling the skipped bytes with zeros. In general, for record files, lseek should only be directed to an absolute position that was returned by a previous valid call to lseek or to the beginning or end of a file. If a call to lseek does not satisfy these conditions, the results are unpredictable. See also open, creat, dup, dup2, and fseek.
3 – Return Values
x The new file position. -1 Indicates that the file descriptor is undefined, or a seek was attempted before the beginning of the file.